int nntp_open_connection(struct NntpAccountData *adata)
{
  struct Connection *conn = adata->conn;
  char buf[256];
  int cap;
  bool posting = false, auth = true;

  if (adata->status == NNTP_OK)
    return 0;
  if (adata->status == NNTP_BYE)
    return -1;
  adata->status = NNTP_NONE;

  if (mutt_socket_open(conn) < 0)
    return -1;

  if (mutt_socket_readln(buf, sizeof(buf), conn) < 0)
    return nntp_connect_error(adata);

  if (mutt_str_startswith(buf, "200", CASE_MATCH))
    posting = true;
  else if (!mutt_str_startswith(buf, "201", CASE_MATCH))
  {
    mutt_socket_close(conn);
    mutt_str_remove_trailing_ws(buf);
    mutt_error("%s", buf);
    return -1;
  }

  /* get initial capabilities */
  cap = nntp_capabilities(adata);
  if (cap < 0)
    return -1;

  /* tell news server to switch to mode reader if it isn't so */
  if (cap > 0)
  {
    if ((mutt_socket_send(conn, "MODE READER\r\n") < 0) ||
        (mutt_socket_readln(buf, sizeof(buf), conn) < 0))
    {
      return nntp_connect_error(adata);
    }

    if (mutt_str_startswith(buf, "200", CASE_MATCH))
      posting = true;
    else if (mutt_str_startswith(buf, "201", CASE_MATCH))
      posting = false;
    /* error if has capabilities, ignore result if no capabilities */
    else if (adata->hasCAPABILITIES)
    {
      mutt_socket_close(conn);
      mutt_error(_("Could not switch to reader mode"));
      return -1;
    }

    /* recheck capabilities after MODE READER */
    if (adata->hasCAPABILITIES)
    {
      cap = nntp_capabilities(adata);
      if (cap < 0)
        return -1;
    }
  }

  mutt_message(_("Connected to %s. %s"), conn->account.host,
               posting ? _("Posting is ok") : _("Posting is NOT ok"));
  mutt_sleep(1);

#ifdef USE_SSL
  /* Attempt STARTTLS if available and desired. */
  if ((adata->use_tls != 1) && (adata->hasSTARTTLS || C_SslForceTls))
  {
    if (adata->use_tls == 0)
    {
      adata->use_tls =
          C_SslForceTls || query_quadoption(C_SslStarttls,
                                            _("Secure connection with TLS?")) == MUTT_YES ?
              2 :
              1;
    }
    if (adata->use_tls == 2)
    {
      if ((mutt_socket_send(conn, "STARTTLS\r\n") < 0) ||
          (mutt_socket_readln(buf, sizeof(buf), conn) < 0))
      {
        return nntp_connect_error(adata);
      }
      if (!mutt_str_startswith(buf, "382", CASE_MATCH))
      {
        adata->use_tls = 0;
        mutt_error("STARTTLS: %s", buf);
      }
      else if (mutt_ssl_starttls(conn))
      {
        adata->use_tls = 0;
        adata->status = NNTP_NONE;
        mutt_socket_close(adata->conn);
        mutt_error(_("Could not negotiate TLS connection"));
        return -1;
      }
      else
      {
        /* recheck capabilities after STARTTLS */
        cap = nntp_capabilities(adata);
        if (cap < 0)
          return -1;
      }
    }
  }
#endif

  /* authentication required? */
  if (conn->account.flags & MUTT_ACCT_USER)
  {
    if (!conn->account.user[0])
      auth = false;
  }
  else
  {
    if ((mutt_socket_send(conn, "STAT\r\n") < 0) ||
        (mutt_socket_readln(buf, sizeof(buf), conn) < 0))
    {
      return nntp_connect_error(adata);
    }
    if (!mutt_str_startswith(buf, "480", CASE_MATCH))
      auth = false;
  }

  /* authenticate */
  if (auth && (nntp_auth(adata) < 0))
    return -1;

  /* get final capabilities after authentication */
  if (adata->hasCAPABILITIES && (auth || (cap > 0)))
  {
    cap = nntp_capabilities(adata);
    if (cap < 0)
      return -1;
    if (cap > 0)
    {
      mutt_socket_close(conn);
      mutt_error(_("Could not switch to reader mode"));
      return -1;
    }
  }

  /* attempt features */
  if (nntp_attempt_features(adata) < 0)
    return -1;

  adata->status = NNTP_OK;
  return 0;
}


static void signal_cb ( int fd , short event , void * arg ) {
 struct event * signal = arg ;
 printf ( "%s: got signal %d\n" , __func__ , EVENT_SIGNAL ( signal ) ) ;
 if ( called >= 2 ) event_del ( signal ) ;
 called ++ ;
 }


static inline uint8_t read_u8 ( const unsigned char * buffer , size_t * pos ) {
 return buffer [ ( * pos ) ++ ] ;
 }


strong_alias ( _nss_nis_setaliasent , _nss_nis_endaliasent ) static enum nss_status internal_nis_getaliasent_r ( struct aliasent * alias , char * buffer , size_t buflen , int * errnop ) {
 char * domain ;
 if ( __builtin_expect ( yp_get_default_domain ( & domain ) , 0 ) ) return NSS_STATUS_UNAVAIL ;
 alias -> alias_local = 0 ;
 int parse_res ;
 do {
 char * result ;
 int len ;
 char * outkey ;
 int keylen ;
 int yperr ;
 if ( new_start ) yperr = yp_first ( domain , "mail.aliases" , & outkey , & keylen , & result , & len ) ;
 else yperr = yp_next ( domain , "mail.aliases" , oldkey , oldkeylen , & outkey , & keylen , & result , & len ) ;
 if ( __builtin_expect ( yperr != YPERR_SUCCESS , 0 ) ) {
 enum nss_status retval = yperr2nss ( yperr ) ;
 if ( retval == NSS_STATUS_TRYAGAIN ) * errnop = errno ;
 return retval ;
 }
 if ( __builtin_expect ( ( size_t ) ( len + 1 ) > buflen , 0 ) ) {
 free ( result ) ;
 * errnop = ERANGE ;
 return NSS_STATUS_TRYAGAIN ;
 }
 char * p = strncpy ( buffer , result , len ) ;
 buffer [ len ] = '\0' ;
 while ( isspace ( * p ) ) ++ p ;
 free ( result ) ;
 parse_res = _nss_nis_parse_aliasent ( outkey , p , alias , buffer , buflen , errnop ) ;
 if ( __builtin_expect ( parse_res == - 1 , 0 ) ) {
 free ( outkey ) ;
 * errnop = ERANGE ;
 return NSS_STATUS_TRYAGAIN ;
 }
 free ( oldkey ) ;
 oldkey = outkey ;
 oldkeylen = keylen ;
 new_start = 0 ;
 }
 while ( ! parse_res ) ;
 return NSS_STATUS_SUCCESS ;
 }


int main ( int argc , char * * argv ) {
 struct st_command * command ;
 my_bool q_send_flag = 0 , abort_flag = 0 ;
 uint command_executed = 0 , last_command_executed = 0 ;
 char save_file [ FN_REFLEN ] ;
 bool empty_result = FALSE ;
 MY_INIT ( argv [ 0 ] ) ;
 DBUG_ENTER ( "main" ) ;
 sf_leaking_memory = 1 ;
 save_file [ 0 ] = 0 ;
 TMPDIR [ 0 ] = 0 ;
 init_signal_handling ( ) ;
 memset ( & saved_expected_errors , 0 , sizeof ( saved_expected_errors ) ) ;
 # ifdef EMBEDDED_LIBRARY ( void ) pthread_attr_init ( & cn_thd_attrib ) ;
 pthread_attr_setstacksize ( & cn_thd_attrib , DEFAULT_THREAD_STACK ) ;
 # endif memset ( file_stack , 0 , sizeof ( file_stack ) ) ;
 file_stack_end = file_stack + ( sizeof ( file_stack ) / sizeof ( struct st_test_file ) ) - 1 ;
 cur_file = file_stack ;
 memset ( block_stack , 0 , sizeof ( block_stack ) ) ;
 block_stack_end = block_stack + ( sizeof ( block_stack ) / sizeof ( struct st_block ) ) - 1 ;
 cur_block = block_stack ;
 cur_block -> ok = TRUE ;
 cur_block -> cmd = cmd_none ;
 my_init_dynamic_array ( & q_lines , sizeof ( struct st_command * ) , 1024 , 1024 ) ;
 if ( my_hash_init2 ( & var_hash , 64 , charset_info , 128 , 0 , 0 , get_var_key , var_free , MYF ( 0 ) ) ) die ( "Variable hash initialization failed" ) ;
 var_set_string ( "MYSQL_SERVER_VERSION" , MYSQL_SERVER_VERSION ) ;
 var_set_string ( "MYSQL_SYSTEM_TYPE" , SYSTEM_TYPE ) ;
 var_set_string ( "MYSQL_MACHINE_TYPE" , MACHINE_TYPE ) ;
 if ( sizeof ( void * ) == 8 ) {
 var_set_string ( "MYSQL_SYSTEM_ARCHITECTURE" , "64" ) ;
 }
 else {
 var_set_string ( "MYSQL_SYSTEM_ARCHITECTURE" , "32" ) ;
 }
 memset ( & master_pos , 0 , sizeof ( master_pos ) ) ;
 parser . current_line = parser . read_lines = 0 ;
 memset ( & var_reg , 0 , sizeof ( var_reg ) ) ;
 init_builtin_echo ( ) ;
 # ifdef __WIN__ # ifndef USE_CYGWIN is_windows = 1 ;
 # endif init_tmp_sh_file ( ) ;
 init_win_path_patterns ( ) ;
 # endif init_dynamic_string ( & ds_res , "" , 2048 , 2048 ) ;
 init_alloc_root ( & require_file_root , 1024 , 1024 ) ;
 parse_args ( argc , argv ) ;
 log_file . open ( opt_logdir , result_file_name , ".log" ) ;
 verbose_msg ( "Logging to '%s'." , log_file . file_name ( ) ) ;
 if ( opt_mark_progress ) {
 progress_file . open ( opt_logdir , result_file_name , ".progress" ) ;
 verbose_msg ( "Tracing progress in '%s'." , progress_file . file_name ( ) ) ;
 }
 connections = ( struct st_connection * ) my_malloc ( ( opt_max_connections + 2 ) * sizeof ( struct st_connection ) , MYF ( MY_WME | MY_ZEROFILL ) ) ;
 connections_end = connections + opt_max_connections + 1 ;
 next_con = connections + 1 ;
 var_set_int ( "$PS_PROTOCOL" , ps_protocol ) ;
 var_set_int ( "$NON_BLOCKING_API" , non_blocking_api_enabled ) ;
 var_set_int ( "$SP_PROTOCOL" , sp_protocol ) ;
 var_set_int ( "$VIEW_PROTOCOL" , view_protocol ) ;
 var_set_int ( "$CURSOR_PROTOCOL" , cursor_protocol ) ;
 var_set_int ( "$ENABLED_QUERY_LOG" , 1 ) ;
 var_set_int ( "$ENABLED_ABORT_ON_ERROR" , 1 ) ;
 var_set_int ( "$ENABLED_RESULT_LOG" , 1 ) ;
 var_set_int ( "$ENABLED_CONNECT_LOG" , 0 ) ;
 var_set_int ( "$ENABLED_WARNINGS" , 1 ) ;
 var_set_int ( "$ENABLED_INFO" , 0 ) ;
 var_set_int ( "$ENABLED_METADATA" , 0 ) ;
 DBUG_PRINT ( "info" , ( "result_file: '%s'" , result_file_name ? result_file_name : "" ) ) ;
 verbose_msg ( "Results saved in '%s'." , result_file_name ? result_file_name : "" ) ;
 if ( mysql_server_init ( embedded_server_arg_count , embedded_server_args , ( char * * ) embedded_server_groups ) ) die ( "Can't initialize MySQL server" ) ;
 server_initialized = 1 ;
 if ( cur_file == file_stack && cur_file -> file == 0 ) {
 cur_file -> file = stdin ;
 cur_file -> file_name = my_strdup ( "<stdin>" , MYF ( MY_WME ) ) ;
 cur_file -> lineno = 1 ;
 }
 var_set_string ( "MYSQLTEST_FILE" , cur_file -> file_name ) ;
 init_re ( ) ;
 if ( cursor_protocol ) ps_protocol = 1 ;
 ps_protocol_enabled = ps_protocol ;
 sp_protocol_enabled = sp_protocol ;
 view_protocol_enabled = view_protocol ;
 cursor_protocol_enabled = cursor_protocol ;
 st_connection * con = connections ;
 init_connection_thd ( con ) ;
 if ( ! ( con -> mysql = mysql_init ( 0 ) ) ) die ( "Failed in mysql_init()" ) ;
 if ( opt_connect_timeout ) mysql_options ( con -> mysql , MYSQL_OPT_CONNECT_TIMEOUT , ( void * ) & opt_connect_timeout ) ;
 if ( opt_compress ) mysql_options ( con -> mysql , MYSQL_OPT_COMPRESS , NullS ) ;
 mysql_options ( con -> mysql , MYSQL_OPT_LOCAL_INFILE , 0 ) ;
 mysql_options ( con -> mysql , MYSQL_SET_CHARSET_NAME , charset_info -> csname ) ;
 if ( opt_charsets_dir ) mysql_options ( con -> mysql , MYSQL_SET_CHARSET_DIR , opt_charsets_dir ) ;
 if ( opt_protocol ) mysql_options ( con -> mysql , MYSQL_OPT_PROTOCOL , ( char * ) & opt_protocol ) ;
 if ( opt_plugin_dir && * opt_plugin_dir ) mysql_options ( con -> mysql , MYSQL_PLUGIN_DIR , opt_plugin_dir ) ;
 # if defined ( HAVE_OPENSSL ) && ! defined ( EMBEDDED_LIBRARY ) if ( opt_use_ssl ) {
 mysql_ssl_set ( con -> mysql , opt_ssl_key , opt_ssl_cert , opt_ssl_ca , opt_ssl_capath , opt_ssl_cipher ) ;
 # if MYSQL_VERSION_ID >= 50000 opt_ssl_verify_server_cert = opt_host && ! strcmp ( opt_host , "localhost" ) ;
 mysql_options ( con -> mysql , MYSQL_OPT_SSL_VERIFY_SERVER_CERT , & opt_ssl_verify_server_cert ) ;
 # endif }
 # endif # ifdef HAVE_SMEM if ( shared_memory_base_name ) mysql_options ( con -> mysql , MYSQL_SHARED_MEMORY_BASE_NAME , shared_memory_base_name ) ;
 # endif if ( ! ( con -> name = my_strdup ( "default" , MYF ( MY_WME ) ) ) ) die ( "Out of memory" ) ;
 mysql_options ( con -> mysql , MYSQL_OPT_NONBLOCK , 0 ) ;
 safe_connect ( con -> mysql , con -> name , opt_host , opt_user , opt_pass , opt_db , opt_port , unix_sock ) ;
 timer_start = timer_now ( ) ;
 var_set_errno ( - 1 ) ;
 set_current_connection ( con ) ;
 if ( opt_prologue ) {
 open_file ( opt_prologue ) ;
 }
 verbose_msg ( "Start processing test commands from '%s' ..." , cur_file -> file_name ) ;
 while ( ! read_command ( & command ) && ! abort_flag ) {
 my_bool ok_to_do ;
 int current_line_inc = 1 , processed = 0 ;
 if ( command -> type == Q_UNKNOWN || command -> type == Q_COMMENT_WITH_COMMAND ) get_command_type ( command ) ;
 if ( parsing_disabled && command -> type != Q_ENABLE_PARSING && command -> type != Q_DISABLE_PARSING ) {
 command -> type = Q_COMMENT ;
 }
 command -> abort_on_error = ( command -> expected_errors . count == 0 && abort_on_error ) ;
 ok_to_do = cur_block -> ok || command -> type == Q_DELIMITER || command -> type == Q_PERL ;
 if ( ! ok_to_do ) {
 if ( command -> type == Q_SOURCE || command -> type == Q_ERROR || command -> type == Q_WRITE_FILE || command -> type == Q_APPEND_FILE ) {
 for ( struct st_block * stb = cur_block - 1 ;
 stb >= block_stack ;
 stb -- ) {
 if ( stb -> cmd == cmd_while ) {
 ok_to_do = 1 ;
 break ;
 }
 }
 }
 }
 if ( ok_to_do ) {
 command -> last_argument = command -> first_argument ;
 processed = 1 ;
 curr_command = command ;
 switch ( command -> type ) {
 case Q_CONNECT : do_connect ( command ) ;
 break ;
 case Q_CONNECTION : select_connection ( command ) ;
 break ;
 case Q_DISCONNECT : case Q_DIRTY_CLOSE : do_close_connection ( command ) ;
 break ;
 case Q_ENABLE_PREPARE_WARNINGS : prepare_warnings_enabled = 1 ;
 break ;
 case Q_DISABLE_PREPARE_WARNINGS : prepare_warnings_enabled = 0 ;
 break ;
 case Q_ENABLE_QUERY_LOG : set_property ( command , P_QUERY , 0 ) ;
 break ;
 case Q_DISABLE_QUERY_LOG : set_property ( command , P_QUERY , 1 ) ;
 break ;
 case Q_ENABLE_ABORT_ON_ERROR : set_property ( command , P_ABORT , 1 ) ;
 break ;
 case Q_DISABLE_ABORT_ON_ERROR : set_property ( command , P_ABORT , 0 ) ;
 break ;
 case Q_ENABLE_RESULT_LOG : set_property ( command , P_RESULT , 0 ) ;
 break ;
 case Q_DISABLE_RESULT_LOG : set_property ( command , P_RESULT , 1 ) ;
 break ;
 case Q_ENABLE_CONNECT_LOG : set_property ( command , P_CONNECT , 0 ) ;
 break ;
 case Q_DISABLE_CONNECT_LOG : set_property ( command , P_CONNECT , 1 ) ;
 break ;
 case Q_ENABLE_WARNINGS : set_property ( command , P_WARN , 0 ) ;
 break ;
 case Q_DISABLE_WARNINGS : set_property ( command , P_WARN , 1 ) ;
 break ;
 case Q_ENABLE_INFO : set_property ( command , P_INFO , 0 ) ;
 break ;
 case Q_DISABLE_INFO : set_property ( command , P_INFO , 1 ) ;
 break ;
 case Q_ENABLE_METADATA : set_property ( command , P_META , 1 ) ;
 break ;
 case Q_DISABLE_METADATA : set_property ( command , P_META , 0 ) ;
 break ;
 case Q_ENABLE_COLUMN_NAMES : disable_column_names = 0 ;
 var_set_int ( "$ENABLED_COLUMN_NAMES" , 0 ) ;
 break ;
 case Q_DISABLE_COLUMN_NAMES : disable_column_names = 1 ;
 var_set_int ( "$ENABLED_COLUMN_NAMES" , 1 ) ;
 break ;
 case Q_SOURCE : do_source ( command ) ;
 break ;
 case Q_SLEEP : do_sleep ( command , 0 ) ;
 break ;
 case Q_REAL_SLEEP : do_sleep ( command , 1 ) ;
 break ;
 case Q_WAIT_FOR_SLAVE_TO_STOP : do_wait_for_slave_to_stop ( command ) ;
 break ;
 case Q_INC : do_modify_var ( command , DO_INC ) ;
 break ;
 case Q_DEC : do_modify_var ( command , DO_DEC ) ;
 break ;
 case Q_ECHO : do_echo ( command ) ;
 command_executed ++ ;
 break ;
 case Q_SYSTEM : do_system ( command ) ;
 break ;
 case Q_REMOVE_FILE : do_remove_file ( command ) ;
 break ;
 case Q_REMOVE_FILES_WILDCARD : do_remove_files_wildcard ( command ) ;
 break ;
 case Q_MKDIR : do_mkdir ( command ) ;
 break ;
 case Q_RMDIR : do_rmdir ( command ) ;
 break ;
 case Q_LIST_FILES : do_list_files ( command ) ;
 break ;
 case Q_LIST_FILES_WRITE_FILE : do_list_files_write_file_command ( command , FALSE ) ;
 break ;
 case Q_LIST_FILES_APPEND_FILE : do_list_files_write_file_command ( command , TRUE ) ;
 break ;
 case Q_FILE_EXIST : do_file_exist ( command ) ;
 break ;
 case Q_WRITE_FILE : do_write_file ( command ) ;
 break ;
 case Q_APPEND_FILE : do_append_file ( command ) ;
 break ;
 case Q_DIFF_FILES : do_diff_files ( command ) ;
 break ;
 case Q_SEND_QUIT : do_send_quit ( command ) ;
 break ;
 case Q_CHANGE_USER : do_change_user ( command ) ;
 break ;
 case Q_CAT_FILE : do_cat_file ( command ) ;
 break ;
 case Q_COPY_FILE : do_copy_file ( command ) ;
 break ;
 case Q_MOVE_FILE : do_move_file ( command ) ;
 break ;
 case Q_CHMOD_FILE : do_chmod_file ( command ) ;
 break ;
 case Q_PERL : do_perl ( command ) ;
 break ;
 case Q_RESULT_FORMAT_VERSION : do_result_format_version ( command ) ;
 break ;
 case Q_DELIMITER : do_delimiter ( command ) ;
 break ;
 case Q_DISPLAY_VERTICAL_RESULTS : display_result_vertically = TRUE ;
 break ;
 case Q_DISPLAY_HORIZONTAL_RESULTS : display_result_vertically = FALSE ;
 break ;
 case Q_SORTED_RESULT : display_result_sorted = TRUE ;
 break ;
 case Q_LOWERCASE : display_result_lower = TRUE ;
 break ;
 case Q_LET : do_let ( command ) ;
 break ;
 case Q_EVAL_RESULT : die ( "'eval_result' command is deprecated" ) ;
 case Q_EVAL : case Q_QUERY_VERTICAL : case Q_QUERY_HORIZONTAL : if ( command -> query == command -> query_buf ) {
 command -> query = command -> first_argument ;
 command -> first_word_len = 0 ;
 }
 case Q_QUERY : case Q_REAP : {
 my_bool old_display_result_vertically = display_result_vertically ;
 int flags = QUERY_REAP_FLAG | QUERY_SEND_FLAG ;
 if ( q_send_flag ) {
 flags = QUERY_SEND_FLAG ;
 q_send_flag = 0 ;
 }
 else if ( command -> type == Q_REAP ) {
 flags = QUERY_REAP_FLAG ;
 }
 display_result_vertically |= ( command -> type == Q_QUERY_VERTICAL ) ;
 if ( save_file [ 0 ] ) {
 if ( ! ( command -> require_file = strdup_root ( & require_file_root , save_file ) ) ) die ( "out of memory for require_file" ) ;
 save_file [ 0 ] = 0 ;
 }
 run_query ( cur_con , command , flags ) ;
 command_executed ++ ;
 command -> last_argument = command -> end ;
 display_result_vertically = old_display_result_vertically ;
 break ;
 }
 case Q_SEND : case Q_SEND_EVAL : if ( ! * command -> first_argument ) {
 q_send_flag = 1 ;
 break ;
 }
 if ( command -> query == command -> query_buf ) command -> query = command -> first_argument ;
 run_query ( cur_con , command , QUERY_SEND_FLAG ) ;
 command_executed ++ ;
 command -> last_argument = command -> end ;
 break ;
 case Q_REQUIRE : do_get_file_name ( command , save_file , sizeof ( save_file ) ) ;
 break ;
 case Q_ERROR : do_get_errcodes ( command ) ;
 break ;
 case Q_REPLACE : do_get_replace ( command ) ;
 break ;
 case Q_REPLACE_REGEX : do_get_replace_regex ( command ) ;
 break ;
 case Q_REPLACE_COLUMN : do_get_replace_column ( command ) ;
 break ;
 case Q_SAVE_MASTER_POS : do_save_master_pos ( ) ;
 break ;
 case Q_SYNC_WITH_MASTER : do_sync_with_master ( command ) ;
 break ;
 case Q_SYNC_SLAVE_WITH_MASTER : {
 do_save_master_pos ( ) ;
 if ( * command -> first_argument ) select_connection ( command ) ;
 else select_connection_name ( "slave" ) ;
 do_sync_with_master2 ( command , 0 ) ;
 break ;
 }
 case Q_COMMENT : {
 command -> last_argument = command -> end ;
 if ( opt_result_format_version == 1 ) break ;
 if ( disable_query_log ) break ;
 const char * p = command -> query ;
 if ( p && * p == '#' && * ( p + 1 ) == '#' ) {
 dynstr_append_mem ( & ds_res , command -> query , command -> query_len ) ;
 dynstr_append ( & ds_res , "\n" ) ;
 }
 break ;
 }
 case Q_EMPTY_LINE : if ( opt_result_format_version == 1 ) break ;
 if ( disable_query_log ) break ;
 dynstr_append ( & ds_res , "\n" ) ;
 break ;
 case Q_PING : handle_command_error ( command , mysql_ping ( cur_con -> mysql ) , - 1 ) ;
 break ;
 case Q_SEND_SHUTDOWN : handle_command_error ( command , mysql_shutdown ( cur_con -> mysql , SHUTDOWN_DEFAULT ) , - 1 ) ;
 break ;
 case Q_SHUTDOWN_SERVER : do_shutdown_server ( command ) ;
 break ;
 case Q_EXEC : do_exec ( command ) ;
 command_executed ++ ;
 break ;
 case Q_START_TIMER : timer_start = timer_now ( ) ;
 break ;
 case Q_END_TIMER : timer_output ( ) ;
 break ;
 case Q_CHARACTER_SET : do_set_charset ( command ) ;
 break ;
 case Q_DISABLE_PS_PROTOCOL : set_property ( command , P_PS , 0 ) ;
 close_statements ( ) ;
 break ;
 case Q_ENABLE_PS_PROTOCOL : set_property ( command , P_PS , ps_protocol ) ;
 break ;
 case Q_DISABLE_NON_BLOCKING_API : non_blocking_api_enabled = 0 ;
 break ;
 case Q_ENABLE_NON_BLOCKING_API : non_blocking_api_enabled = 1 ;
 break ;
 case Q_DISABLE_RECONNECT : set_reconnect ( cur_con -> mysql , 0 ) ;
 break ;
 case Q_ENABLE_RECONNECT : set_reconnect ( cur_con -> mysql , 1 ) ;
 close_statements ( ) ;
 break ;
 case Q_DISABLE_PARSING : if ( parsing_disabled == 0 ) parsing_disabled = 1 ;
 else report_or_die ( "Parsing is already disabled" ) ;
 break ;
 case Q_ENABLE_PARSING : if ( parsing_disabled == 1 ) parsing_disabled = 0 ;
 else report_or_die ( "Parsing is already enabled" ) ;
 break ;
 case Q_DIE : die ( "%s" , command -> first_argument ) ;
 break ;
 case Q_EXIT : abort_flag = 1 ;
 break ;
 case Q_SKIP : dynstr_set ( & ds_res , 0 ) ;
 do_eval ( & ds_res , command -> first_argument , command -> end , FALSE ) ;
 abort_not_supported_test ( "%s" , ds_res . str ) ;
 break ;
 case Q_RESULT : die ( "result, deprecated command" ) ;
 break ;
 default : processed = 0 ;
 break ;
 }
 }
 if ( ! processed ) {
 current_line_inc = 0 ;
 switch ( command -> type ) {
 case Q_WHILE : do_block ( cmd_while , command ) ;
 break ;
 case Q_IF : do_block ( cmd_if , command ) ;
 break ;
 case Q_END_BLOCK : do_done ( command ) ;
 break ;
 default : current_line_inc = 1 ;
 break ;
 }
 }
 else check_eol_junk ( command -> last_argument ) ;
 if ( command -> type != Q_ERROR && command -> type != Q_COMMENT ) {
 memset ( & saved_expected_errors , 0 , sizeof ( saved_expected_errors ) ) ;
 }
 if ( command_executed != last_command_executed || command -> used_replace ) {
 free_all_replace ( ) ;
 display_result_sorted = FALSE ;
 display_result_lower = FALSE ;
 }
 last_command_executed = command_executed ;
 parser . current_line += current_line_inc ;
 if ( opt_mark_progress ) mark_progress ( command , parser . current_line ) ;
 log_file . write ( & ds_res ) ;
 log_file . flush ( ) ;
 dynstr_set ( & ds_res , 0 ) ;
 }
 log_file . close ( ) ;
 start_lineno = 0 ;
 verbose_msg ( "... Done processing test commands." ) ;
 if ( parsing_disabled ) die ( "Test ended with parsing disabled" ) ;
 if ( log_file . bytes_written ( ) ) {
 if ( result_file_name ) {
 if ( record ) {
 if ( my_copy ( log_file . file_name ( ) , result_file_name , MYF ( 0 ) ) != 0 ) die ( "Failed to copy '%s' to '%s', errno: %d" , log_file . file_name ( ) , result_file_name , errno ) ;
 }
 else {
 check_result ( ) ;
 }
 }
 }
 else {
 if ( ! result_file_name || record || compare_files ( log_file . file_name ( ) , result_file_name ) ) {
 die ( "The test didn't produce any output" ) ;
 }
 else {
 empty_result = TRUE ;
 }
 }
 if ( ! command_executed && result_file_name && ! empty_result ) die ( "No queries executed but non-empty result file found!" ) ;
 verbose_msg ( "Test has succeeded!" ) ;
 timer_output ( ) ;
 cleanup_and_exit ( 0 ) ;
 return 0 ;
 }


static av_cold int color_init(AVFilterContext *ctx, const char *args, void *opaque) { ColorContext *color = ctx->priv; char color_string[128] = "black"; char frame_size [128] = "320x240"; char frame_rate [128] = "25"; AVRational frame_rate_q; char *colon = 0, *equal = 0; int ret = 0; color->class = &color_class; if (args) { colon = strchr(args, ':'); equal = strchr(args, '='); } if (!args || (equal && (!colon || equal < colon))) { av_opt_set_defaults(color); if ((ret = av_set_options_string(color, args, "=", ":")) < 0) { av_log(ctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args); goto end; } if (av_parse_video_rate(&frame_rate_q, color->rate_str) < 0 || frame_rate_q.den <= 0 || frame_rate_q.num <= 0) { av_log(ctx, AV_LOG_ERROR, "Invalid frame rate: %s\n", color->rate_str); ret = AVERROR(EINVAL); goto end; } if (av_parse_color(color->color_rgba, color->color_str, -1, ctx) < 0) { ret = AVERROR(EINVAL); goto end; } } else { av_log(ctx, AV_LOG_WARNING, "Flat options syntax is deprecated, use key=value pairs.\n"); sscanf(args, "%127[^:]:%127[^:]:%127s", color_string, frame_size, frame_rate); if (av_parse_video_size(&color->w, &color->h, frame_size) < 0) { av_log(ctx, AV_LOG_ERROR, "Invalid frame size: %s\n", frame_size); return AVERROR(EINVAL); } if (av_parse_video_rate(&frame_rate_q, frame_rate) < 0 || frame_rate_q.den <= 0 || frame_rate_q.num <= 0) { av_log(ctx, AV_LOG_ERROR, "Invalid frame rate: %s\n", frame_rate); return AVERROR(EINVAL); } if (av_parse_color(color->color_rgba, color_string, -1, ctx) < 0) return AVERROR(EINVAL); } color->time_base.num = frame_rate_q.den; color->time_base.den = frame_rate_q.num; end: av_opt_free(color); return ret; }


void LibRaw::parse_exif(int base)
{
  unsigned entries, tag, type, len, save, c;
  double expo, ape;

  unsigned kodak = !strncmp(make, "EASTMAN", 7) && tiff_nifds < 3;

  entries = get2();
  if (!strncmp(make, "Hasselblad", 10) && (tiff_nifds > 3) && (entries > 512))
    return;
  INT64 fsize = ifp->size();
  while (entries--)
  {
    tiff_get(base, &tag, &type, &len, &save);

    INT64 savepos = ftell(ifp);
    if (len > 8 && savepos + len > fsize * 2)
    {
      fseek(ifp, save, SEEK_SET); // Recover tiff-read position!!
      continue;
    }
    if (callbacks.exif_cb)
    {
      callbacks.exif_cb(callbacks.exifparser_data, tag, type, len, order, ifp,
                        base);
      fseek(ifp, savepos, SEEK_SET);
    }

    switch (tag)
    {
	case 0xA005: // Interoperability IFD
		fseek(ifp, get4() + base, SEEK_SET);
		parse_exif_interop(base);
		break;
	case 0xA001: // ExifIFD.ColorSpace
		c = get2();
		if (c == 1 && imgdata.color.ExifColorSpace == LIBRAW_COLORSPACE_Unknown)
			imgdata.color.ExifColorSpace = LIBRAW_COLORSPACE_sRGB;
		else if (c == 2)
			imgdata.color.ExifColorSpace = LIBRAW_COLORSPACE_AdobeRGB;
		break;
    case 0x9400:
      imCommon.exifAmbientTemperature = getreal(type);
      if ((imCommon.CameraTemperature > -273.15f) &&
          ((OlyID == OlyID_TG_5) ||
           (OlyID == OlyID_TG_6))
      )
        imCommon.CameraTemperature += imCommon.exifAmbientTemperature;
      break;
    case 0x9401:
      imCommon.exifHumidity = getreal(type);
      break;
    case 0x9402:
      imCommon.exifPressure = getreal(type);
      break;
    case 0x9403:
      imCommon.exifWaterDepth = getreal(type);
      break;
    case 0x9404:
      imCommon.exifAcceleration = getreal(type);
      break;
    case 0x9405:
      imCommon.exifCameraElevationAngle = getreal(type);
      break;

    case 0xa405: // FocalLengthIn35mmFormat
      imgdata.lens.FocalLengthIn35mmFormat = get2();
      break;
    case 0xa431: // BodySerialNumber
      stmread(imgdata.shootinginfo.BodySerial, len, ifp);
      break;
    case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard
      imgdata.lens.MinFocal = getreal(type);
      imgdata.lens.MaxFocal = getreal(type);
      imgdata.lens.MaxAp4MinFocal = getreal(type);
      imgdata.lens.MaxAp4MaxFocal = getreal(type);
      break;
    case 0xa435: // LensSerialNumber
      stmread(imgdata.lens.LensSerial, len, ifp);
      if (!strncmp(imgdata.lens.LensSerial, "----", 4))
        imgdata.lens.LensSerial[0] = '\0';
      break;
    case 0xa420: /* 42016, ImageUniqueID */
      stmread(imgdata.color.ImageUniqueID, len, ifp);
      break;
    case 0xc65d: /* 50781, RawDataUniqueID */
      imgdata.color.RawDataUniqueID[16] = 0;
      fread(imgdata.color.RawDataUniqueID, 1, 16, ifp);
      break;
    case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard
      imgdata.lens.dng.MinFocal = getreal(type);
      imgdata.lens.dng.MaxFocal = getreal(type);
      imgdata.lens.dng.MaxAp4MinFocal = getreal(type);
      imgdata.lens.dng.MaxAp4MaxFocal = getreal(type);
      break;
    case 0xc68b: /* 50827, OriginalRawFileName */
      stmread(imgdata.color.OriginalRawFileName, len, ifp);
      break;
    case 0xa433: // LensMake
      stmread(imgdata.lens.LensMake, len, ifp);
      break;
    case 0xa434: // LensModel
      stmread(imgdata.lens.Lens, len, ifp);
      if (!strncmp(imgdata.lens.Lens, "----", 4))
        imgdata.lens.Lens[0] = '\0';
      break;
    case 0x9205:
      imgdata.lens.EXIF_MaxAp = libraw_powf64l(2.0f, (getreal(type) / 2.0f));
      break;
    case 0x829a: // 33434
      tiff_ifd[tiff_nifds - 1].t_shutter = shutter = getreal(type);
      break;
    case 0x829d: // 33437, FNumber
      aperture = getreal(type);
      break;
    case 0x8827: // 34855
      iso_speed = get2();
      break;
    case 0x8831: // 34865
      if (iso_speed == 0xffff && !strncasecmp(make, "FUJI", 4))
        iso_speed = getreal(type);
      break;
    case 0x8832: // 34866
      if (iso_speed == 0xffff &&
          (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "CANON", 5)))
        iso_speed = getreal(type);
      break;
    case 0x9003: // 36867
    case 0x9004: // 36868
      get_timestamp(0);
      break;
    case 0x9201: // 37377
      if ((expo = -getreal(type)) < 128 && shutter == 0.)
        tiff_ifd[tiff_nifds - 1].t_shutter = shutter =
            libraw_powf64l(2.0, expo);
      break;
    case 0x9202: // 37378 ApertureValue
      if ((fabs(ape = getreal(type)) < 256.0) && (!aperture))
        aperture = libraw_powf64l(2.0, ape / 2);
      break;
    case 0x9209: // 37385
      flash_used = getreal(type);
      break;
    case 0x920a: // 37386
      focal_len = getreal(type);
      break;
    case 0x927c: // 37500
      if (((make[0] == '\0') && !strncmp(model, "ov5647", 6)) ||
          (!strncmp(make, "RaspberryPi", 11) &&
           (!strncmp(model, "RP_OV5647", 9) ||
            !strncmp(model, "RP_imx219", 9))))
      {
        char mn_text[512];
        char *pos;
        char ccms[512];
        ushort l;
        float num;

        fgets(mn_text, MIN(len, 511), ifp);
        mn_text[511] = 0;

        pos = strstr(mn_text, "gain_r=");
        if (pos)
          cam_mul[0] = atof(pos + 7);
        pos = strstr(mn_text, "gain_b=");
        if (pos)
          cam_mul[2] = atof(pos + 7);
        if ((cam_mul[0] > 0.001f) && (cam_mul[2] > 0.001f))
          cam_mul[1] = cam_mul[3] = 1.0f;
        else
          cam_mul[0] = cam_mul[2] = 0.0f;

        pos = strstr(mn_text, "ccm=");
        if (pos)
        {
          pos += 4;
          char *pos2 = strstr(pos, " ");
          if (pos2)
          {
            l = pos2 - pos;
            memcpy(ccms, pos, l);
            ccms[l] = '\0';
#ifdef LIBRAW_WIN32_CALLS
            // Win32 strtok is already thread-safe
            pos = strtok(ccms, ",");
#else
            char *last = 0;
            pos = strtok_r(ccms, ",", &last);
#endif
            if (pos)
            {
              for (l = 0; l < 4; l++)
              {
                num = 0.0;
                for (c = 0; c < 3; c++)
                {
                  imgdata.color.ccm[l][c] = (float)atoi(pos);
                  num += imgdata.color.ccm[l][c];
#ifdef LIBRAW_WIN32_CALLS
                  pos = strtok(NULL, ",");
#else
                  pos = strtok_r(NULL, ",", &last);
#endif
                  if (!pos)
                    goto end; // broken
                }
                if (num > 0.01)
                  FORC3 imgdata.color.ccm[l][c] = imgdata.color.ccm[l][c] / num;
              }
            }
          }
        }
      end:;
      }
      else if (!strncmp(make, "SONY", 4) &&
               (!strncmp(model, "DSC-V3", 6) || !strncmp(model, "DSC-F828", 8)))
      {
        parseSonySRF(len);
        break;
      }
      else if ((len == 1) && !strncmp(make, "NIKON", 5))
      {
        c = get4();
        if (c)
          fseek(ifp, c, SEEK_SET);
        is_NikonTransfer = 1;
      }
      parse_makernote(base, 0);
      break;
    case 0xa002: // 40962
      if (kodak)
        raw_width = get4();
      break;
    case 0xa003: // 40963
      if (kodak)
        raw_height = get4();
      break;
    case 0xa302: // 41730
      if (get4() == 0x20002)
        for (exif_cfa = c = 0; c < 8; c += 2)
          exif_cfa |= fgetc(ifp) * 0x01010101U << c;
    }
    fseek(ifp, save, SEEK_SET);
  }
}


static int mpeg_decode_slice(Mpeg1Context *s1, int mb_y, const uint8_t **buf, int buf_size) { MpegEncContext *s = &s1->mpeg_enc_ctx; AVCodecContext *avctx= s->avctx; int ret; const int field_pic= s->picture_structure != PICT_FRAME; s->resync_mb_x= s->resync_mb_y= -1; if (mb_y >= s->mb_height){ av_log(s->avctx, AV_LOG_ERROR, "slice below image (%d >= %d)\n", s->mb_y, s->mb_height); return -1; } init_get_bits(&s->gb, *buf, buf_size*8); ff_mpeg1_clean_buffers(s); s->interlaced_dct = 0; s->qscale = get_qscale(s); if(s->qscale == 0){ av_log(s->avctx, AV_LOG_ERROR, "qscale == 0\n"); return -1; } /* extra slice info */ while (get_bits1(&s->gb) != 0) { skip_bits(&s->gb, 8); } s->mb_x=0; for(;;) { int code = get_vlc2(&s->gb, mbincr_vlc.table, MBINCR_VLC_BITS, 2); if (code < 0){ av_log(s->avctx, AV_LOG_ERROR, "first mb_incr damaged\n"); return -1; } if (code >= 33) { if (code == 33) { s->mb_x += 33; } /* otherwise, stuffing, nothing to do */ } else { s->mb_x += code; break; } } s->resync_mb_x= s->mb_x; s->resync_mb_y= s->mb_y= mb_y; s->mb_skip_run= 0; ff_init_block_index(s); if (s->mb_y==0 && s->mb_x==0 && (s->first_field || s->picture_structure==PICT_FRAME)) { if(s->avctx->debug&FF_DEBUG_PICT_INFO){ av_log(s->avctx, AV_LOG_DEBUG, "qp:%d fc:%2d%2d%2d%2d %s %s %s %s %s dc:%d pstruct:%d fdct:%d cmv:%d qtype:%d ivlc:%d rff:%d %s\n", s->qscale, s->mpeg_f_code[0][0],s->mpeg_f_code[0][1],s->mpeg_f_code[1][0],s->mpeg_f_code[1][1], s->pict_type == I_TYPE ? "I" : (s->pict_type == P_TYPE ? "P" : (s->pict_type == B_TYPE ? "B" : "S")), s->progressive_sequence ? "ps" :"", s->progressive_frame ? "pf" : "", s->alternate_scan ? "alt" :"", s->top_field_first ? "top" :"", s->intra_dc_precision, s->picture_structure, s->frame_pred_frame_dct, s->concealment_motion_vectors, s->q_scale_type, s->intra_vlc_format, s->repeat_first_field, s->chroma_420_type ? "420" :""); } } for(;;) { #ifdef HAVE_XVMC //one 1 we memcpy blocks in xvmcvideo if(s->avctx->xvmc_acceleration > 1) XVMC_init_block(s);//set s->block #endif s->dsp.clear_blocks(s->block[0]); ret = mpeg_decode_mb(s, s->block); s->chroma_qscale= s->qscale; dprintf("ret=%d\n", ret); if (ret < 0) return -1; if(s->current_picture.motion_val[0] && !s->encoding){ //note motion_val is normally NULL unless we want to extract the MVs const int wrap = field_pic ? 2*s->b8_stride : s->b8_stride; int xy = s->mb_x*2 + s->mb_y*2*wrap; int motion_x, motion_y, dir, i; if(field_pic && !s->first_field) xy += wrap/2; for(i=0; i<2; i++){ for(dir=0; dir<2; dir++){ if (s->mb_intra || (dir==1 && s->pict_type != B_TYPE)) { motion_x = motion_y = 0; }else if (s->mv_type == MV_TYPE_16X16 || (s->mv_type == MV_TYPE_FIELD && field_pic)){ motion_x = s->mv[dir][0][0]; motion_y = s->mv[dir][0][1]; } else /*if ((s->mv_type == MV_TYPE_FIELD) || (s->mv_type == MV_TYPE_16X8))*/ { motion_x = s->mv[dir][i][0]; motion_y = s->mv[dir][i][1]; } s->current_picture.motion_val[dir][xy ][0] = motion_x; s->current_picture.motion_val[dir][xy ][1] = motion_y; s->current_picture.motion_val[dir][xy + 1][0] = motion_x; s->current_picture.motion_val[dir][xy + 1][1] = motion_y; s->current_picture.ref_index [dir][xy ]= s->current_picture.ref_index [dir][xy + 1]= s->field_select[dir][i]; } xy += wrap; } } s->dest[0] += 16; s->dest[1] += 8; s->dest[2] += 8; MPV_decode_mb(s, s->block); if (++s->mb_x >= s->mb_width) { ff_draw_horiz_band(s, 16*s->mb_y, 16); s->mb_x = 0; s->mb_y++; if(s->mb_y<<field_pic >= s->mb_height){ int left= s->gb.size_in_bits - get_bits_count(&s->gb); if(left < 0 || (left && show_bits(&s->gb, FFMIN(left, 23))) || (avctx->error_resilience >= FF_ER_AGGRESSIVE && left>8)){ av_log(avctx, AV_LOG_ERROR, "end mismatch left=%d\n", left); return -1; }else goto eos; } ff_init_block_index(s); } /* skip mb handling */ if (s->mb_skip_run == -1) { /* read again increment */ s->mb_skip_run = 0; for(;;) { int code = get_vlc2(&s->gb, mbincr_vlc.table, MBINCR_VLC_BITS, 2); if (code < 0){ av_log(s->avctx, AV_LOG_ERROR, "mb incr damaged\n"); return -1; } if (code >= 33) { if (code == 33) { s->mb_skip_run += 33; }else if(code == 35){ if(s->mb_skip_run != 0 || show_bits(&s->gb, 15) != 0){ av_log(s->avctx, AV_LOG_ERROR, "slice mismatch\n"); return -1; } goto eos; /* end of slice */ } /* otherwise, stuffing, nothing to do */ } else { s->mb_skip_run += code; break; } } } } eos: // end of slice *buf += get_bits_count(&s->gb)/8 - 1; //printf("y %d %d %d %d\n", s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y); return 0; }


void LibRaw::kodak_thumb_loader()
{
  INT64 est_datasize =
      T.theight * T.twidth / 3; // is 0.3 bytes per pixel good estimate?
  if (ID.toffset < 0)
    throw LIBRAW_EXCEPTION_IO_CORRUPT;

  if (ID.toffset + est_datasize > ID.input->size() + THUMB_READ_BEYOND)
    throw LIBRAW_EXCEPTION_IO_EOF;

  // some kodak cameras
  ushort s_height = S.height, s_width = S.width, s_iwidth = S.iwidth,
         s_iheight = S.iheight;
  ushort s_flags = libraw_internal_data.unpacker_data.load_flags;
  libraw_internal_data.unpacker_data.load_flags = 12;
  int s_colors = P1.colors;
  unsigned s_filters = P1.filters;
  ushort(*s_image)[4] = imgdata.image;

  S.height = T.theight;
  S.width = T.twidth;
  P1.filters = 0;

  if (thumb_load_raw == &LibRaw::kodak_ycbcr_load_raw)
  {
    S.height += S.height & 1;
    S.width += S.width & 1;
  }

  imgdata.image =
      (ushort(*)[4])calloc(S.iheight * S.iwidth, sizeof(*imgdata.image));
  merror(imgdata.image, "LibRaw::kodak_thumb_loader()");

  ID.input->seek(ID.toffset, SEEK_SET);
  // read kodak thumbnail into T.image[]
  try
  {
    (this->*thumb_load_raw)();
  }
  catch (...)
  {
    free(imgdata.image);
    imgdata.image = s_image;

    T.twidth = 0;
    S.width = s_width;

    S.iwidth = s_iwidth;
    S.iheight = s_iheight;

    T.theight = 0;
    S.height = s_height;

    T.tcolors = 0;
    P1.colors = s_colors;

    P1.filters = s_filters;
    T.tlength = 0;
    libraw_internal_data.unpacker_data.load_flags = s_flags;
    return;
  }

  // from scale_colors
  {
    double dmax;
    float scale_mul[4];
    int c, val;
    for (dmax = DBL_MAX, c = 0; c < 3; c++)
      if (dmax > C.pre_mul[c])
        dmax = C.pre_mul[c];

    for (c = 0; c < 3; c++)
      scale_mul[c] = (C.pre_mul[c] / dmax) * 65535.0 / C.maximum;
    scale_mul[3] = scale_mul[1];

    size_t size = S.height * S.width;
    for (unsigned i = 0; i < size * 4; i++)
    {
      val = imgdata.image[0][i];
      if (!val)
        continue;
      val *= scale_mul[i & 3];
      imgdata.image[0][i] = CLIP(val);
    }
  }

  // from convert_to_rgb
  ushort *img;
  int row, col;

  int(*t_hist)[LIBRAW_HISTOGRAM_SIZE] =
      (int(*)[LIBRAW_HISTOGRAM_SIZE])calloc(sizeof(*t_hist), 4);
  merror(t_hist, "LibRaw::kodak_thumb_loader()");

  float out[3], out_cam[3][4] = {{2.81761312, -1.98369181, 0.166078627, 0},
                                 {-0.111855984, 1.73688626, -0.625030339, 0},
                                 {-0.0379119813, -0.891268849, 1.92918086, 0}};

  for (img = imgdata.image[0], row = 0; row < S.height; row++)
    for (col = 0; col < S.width; col++, img += 4)
    {
      out[0] = out[1] = out[2] = 0;
      int c;
      for (c = 0; c < 3; c++)
      {
        out[0] += out_cam[0][c] * img[c];
        out[1] += out_cam[1][c] * img[c];
        out[2] += out_cam[2][c] * img[c];
      }
      for (c = 0; c < 3; c++)
        img[c] = CLIP((int)out[c]);
      for (c = 0; c < P1.colors; c++)
        t_hist[c][img[c] >> 3]++;
    }

  // from gamma_lut
  int(*save_hist)[LIBRAW_HISTOGRAM_SIZE] =
      libraw_internal_data.output_data.histogram;
  libraw_internal_data.output_data.histogram = t_hist;

  // make curve output curve!
  ushort *t_curve = (ushort *)calloc(sizeof(C.curve), 1);
  merror(t_curve, "LibRaw::kodak_thumb_loader()");
  memmove(t_curve, C.curve, sizeof(C.curve));
  memset(C.curve, 0, sizeof(C.curve));
  {
    int perc, val, total, t_white = 0x2000, c;

    perc = S.width * S.height * 0.01; /* 99th percentile white level */
    if (IO.fuji_width)
      perc /= 2;
    if (!((O.highlight & ~2) || O.no_auto_bright))
      for (t_white = c = 0; c < P1.colors; c++)
      {
        for (val = 0x2000, total = 0; --val > 32;)
          if ((total += libraw_internal_data.output_data.histogram[c][val]) >
              perc)
            break;
        if (t_white < val)
          t_white = val;
      }
    gamma_curve(O.gamm[0], O.gamm[1], 2, (t_white << 3) / O.bright);
  }

  libraw_internal_data.output_data.histogram = save_hist;
  free(t_hist);

  // from write_ppm_tiff - copy pixels into bitmap

  int s_flip = imgdata.sizes.flip;
  if (imgdata.params.raw_processing_options &
      LIBRAW_PROCESSING_NO_ROTATE_FOR_KODAK_THUMBNAILS)
    imgdata.sizes.flip = 0;

  S.iheight = S.height;
  S.iwidth = S.width;
  if (S.flip & 4)
    SWAP(S.height, S.width);

  if (T.thumb)
    free(T.thumb);
  T.thumb = (char *)calloc(S.width * S.height, P1.colors);
  merror(T.thumb, "LibRaw::kodak_thumb_loader()");
  T.tlength = S.width * S.height * P1.colors;

  // from write_tiff_ppm
  {
    int soff = flip_index(0, 0);
    int cstep = flip_index(0, 1) - soff;
    int rstep = flip_index(1, 0) - flip_index(0, S.width);

    for (int row = 0; row < S.height; row++, soff += rstep)
    {
      char *ppm = T.thumb + row * S.width * P1.colors;
      for (int col = 0; col < S.width; col++, soff += cstep)
        for (int c = 0; c < P1.colors; c++)
          ppm[col * P1.colors + c] =
              imgdata.color.curve[imgdata.image[soff][c]] >> 8;
    }
  }

  memmove(C.curve, t_curve, sizeof(C.curve));
  free(t_curve);

  // restore variables
  free(imgdata.image);
  imgdata.image = s_image;

  if (imgdata.params.raw_processing_options &
      LIBRAW_PROCESSING_NO_ROTATE_FOR_KODAK_THUMBNAILS)
    imgdata.sizes.flip = s_flip;

  T.twidth = S.width;
  S.width = s_width;

  S.iwidth = s_iwidth;
  S.iheight = s_iheight;

  T.theight = S.height;
  S.height = s_height;

  T.tcolors = P1.colors;
  P1.colors = s_colors;

  P1.filters = s_filters;
  libraw_internal_data.unpacker_data.load_flags = s_flags;
}


static PyTypeObject* make_type(char *type, PyTypeObject* base, char**fields, int num_fields)
{
    _Py_IDENTIFIER(__module__);
    _Py_IDENTIFIER(_ast3);
    PyObject *fnames, *result;
    int i;
    fnames = PyTuple_New(num_fields);
    if (!fnames) return NULL;
    for (i = 0; i < num_fields; i++) {
        PyObject *field = PyUnicode_FromString(fields[i]);
        if (!field) {
            Py_DECREF(fnames);
            return NULL;
        }
        PyTuple_SET_ITEM(fnames, i, field);
    }
    result = PyObject_CallFunction((PyObject*)&PyType_Type, "s(O){OOOO}",
                    type, base,
                    _PyUnicode_FromId(&PyId__fields), fnames,
                    _PyUnicode_FromId(&PyId___module__),
                    _PyUnicode_FromId(&PyId__ast3));
    Py_DECREF(fnames);
    return (PyTypeObject*)result;
}


static void show_object ( struct object * obj , const struct name_path * path , const char * component , void * cb_data ) {
 struct rev_list_info * info = cb_data ;
 finish_object ( obj , path , component , cb_data ) ;
 if ( info -> flags & REV_LIST_QUIET ) return ;
 show_object_with_name ( stdout , obj , path , component ) ;
 }


obj2ast_arg(PyObject* obj, arg_ty* out, PyArena* arena)
{
    PyObject* tmp = NULL;
    identifier arg;
    expr_ty annotation;
    string type_comment;
    int lineno;
    int col_offset;

    if (lookup_attr_id(obj, &PyId_arg, &tmp) < 0) {
        return 1;
    }
    if (tmp == NULL) {
        PyErr_SetString(PyExc_TypeError, "required field \"arg\" missing from arg");
        return 1;
    }
    else {
        int res;
        res = obj2ast_identifier(tmp, &arg, arena);
        if (res != 0) goto failed;
        Py_CLEAR(tmp);
    }
    if (lookup_attr_id(obj, &PyId_annotation, &tmp) < 0) {
        return 1;
    }
    if (tmp == NULL || tmp == Py_None) {
        Py_CLEAR(tmp);
        annotation = NULL;
    }
    else {
        int res;
        res = obj2ast_expr(tmp, &annotation, arena);
        if (res != 0) goto failed;
        Py_CLEAR(tmp);
    }
    if (lookup_attr_id(obj, &PyId_type_comment, &tmp) < 0) {
        return 1;
    }
    if (tmp == NULL || tmp == Py_None) {
        Py_CLEAR(tmp);
        type_comment = NULL;
    }
    else {
        int res;
        res = obj2ast_string(tmp, &type_comment, arena);
        if (res != 0) goto failed;
        Py_CLEAR(tmp);
    }
    if (lookup_attr_id(obj, &PyId_lineno, &tmp) < 0) {
        return 1;
    }
    if (tmp == NULL) {
        PyErr_SetString(PyExc_TypeError, "required field \"lineno\" missing from arg");
        return 1;
    }
    else {
        int res;
        res = obj2ast_int(tmp, &lineno, arena);
        if (res != 0) goto failed;
        Py_CLEAR(tmp);
    }
    if (lookup_attr_id(obj, &PyId_col_offset, &tmp) < 0) {
        return 1;
    }
    if (tmp == NULL) {
        PyErr_SetString(PyExc_TypeError, "required field \"col_offset\" missing from arg");
        return 1;
    }
    else {
        int res;
        res = obj2ast_int(tmp, &col_offset, arena);
        if (res != 0) goto failed;
        Py_CLEAR(tmp);
    }
    *out = arg(arg, annotation, type_comment, lineno, col_offset, arena);
    return 0;
failed:
    Py_XDECREF(tmp);
    return 1;
}


proto_item * proto_item_get_parent ( const proto_item * ti ) {
 if ( ! ti ) return NULL ;
 return ti -> parent ;
 }


static int restore_sigcontext(CPUAlphaState *env, struct target_sigcontext *sc) { uint64_t fpcr; int i, err = 0; __get_user(env->pc, &sc->sc_pc); for (i = 0; i < 31; ++i) { __get_user(env->ir[i], &sc->sc_regs[i]); } for (i = 0; i < 31; ++i) { __get_user(env->fir[i], &sc->sc_fpregs[i]); } __get_user(fpcr, &sc->sc_fpcr); cpu_alpha_store_fpcr(env, fpcr); return err; }


obj2ast_type_ignore(PyObject* obj, type_ignore_ty* out, PyArena* arena)
{
    int isinstance;

    PyObject *tmp = NULL;

    if (obj == Py_None) {
        *out = NULL;
        return 0;
    }
    isinstance = PyObject_IsInstance(obj, (PyObject*)TypeIgnore_type);
    if (isinstance == -1) {
        return 1;
    }
    if (isinstance) {
        int lineno;

        if (lookup_attr_id(obj, &PyId_lineno, &tmp) < 0) {
            return 1;
        }
        if (tmp == NULL) {
            PyErr_SetString(PyExc_TypeError, "required field \"lineno\" missing from TypeIgnore");
            return 1;
        }
        else {
            int res;
            res = obj2ast_int(tmp, &lineno, arena);
            if (res != 0) goto failed;
            Py_CLEAR(tmp);
        }
        *out = TypeIgnore(lineno, arena);
        if (*out == NULL) goto failed;
        return 0;
    }

    PyErr_Format(PyExc_TypeError, "expected some sort of type_ignore, but got %R", obj);
    failed:
    Py_XDECREF(tmp);
    return 1;
}


obj2ast_withitem(PyObject* obj, withitem_ty* out, PyArena* arena)
{
    PyObject* tmp = NULL;
    expr_ty context_expr;
    expr_ty optional_vars;

    if (_PyObject_HasAttrId(obj, &PyId_context_expr)) {
        int res;
        tmp = _PyObject_GetAttrId(obj, &PyId_context_expr);
        if (tmp == NULL) goto failed;
        res = obj2ast_expr(tmp, &context_expr, arena);
        if (res != 0) goto failed;
        Py_CLEAR(tmp);
    } else {
        PyErr_SetString(PyExc_TypeError, "required field \"context_expr\" missing from withitem");
        return 1;
    }
    if (exists_not_none(obj, &PyId_optional_vars)) {
        int res;
        tmp = _PyObject_GetAttrId(obj, &PyId_optional_vars);
        if (tmp == NULL) goto failed;
        res = obj2ast_expr(tmp, &optional_vars, arena);
        if (res != 0) goto failed;
        Py_CLEAR(tmp);
    } else {
        optional_vars = NULL;
    }
    *out = withitem(context_expr, optional_vars, arena);
    return 0;
failed:
    Py_XDECREF(tmp);
    return 1;
}


static void synthfilt_build_sb_samples (QDM2Context *q, GetBitContext *gb, int length, int sb_min, int sb_max) { int sb, j, k, n, ch, run, channels; int joined_stereo, zero_encoding, chs; int type34_first; float type34_div = 0; float type34_predictor; float samples[10], sign_bits[16]; if (length == 0) { // If no data use noise for (sb=sb_min; sb < sb_max; sb++) build_sb_samples_from_noise (q, sb); return; } for (sb = sb_min; sb < sb_max; sb++) { FIX_NOISE_IDX(q->noise_idx); channels = q->nb_channels; if (q->nb_channels <= 1 || sb < 12) joined_stereo = 0; else if (sb >= 24) joined_stereo = 1; else joined_stereo = (BITS_LEFT(length,gb) >= 1) ? get_bits1 (gb) : 0; if (joined_stereo) { if (BITS_LEFT(length,gb) >= 16) for (j = 0; j < 16; j++) sign_bits[j] = get_bits1 (gb); for (j = 0; j < 64; j++) if (q->coding_method[1][sb][j] > q->coding_method[0][sb][j]) q->coding_method[0][sb][j] = q->coding_method[1][sb][j]; fix_coding_method_array(sb, q->nb_channels, q->coding_method); channels = 1; } for (ch = 0; ch < channels; ch++) { zero_encoding = (BITS_LEFT(length,gb) >= 1) ? get_bits1(gb) : 0; type34_predictor = 0.0; type34_first = 1; for (j = 0; j < 128; ) { switch (q->coding_method[ch][sb][j / 2]) { case 8: if (BITS_LEFT(length,gb) >= 10) { if (zero_encoding) { for (k = 0; k < 5; k++) { if ((j + 2 * k) >= 128) break; samples[2 * k] = get_bits1(gb) ? dequant_1bit[joined_stereo][2 * get_bits1(gb)] : 0; } } else { n = get_bits(gb, 8); for (k = 0; k < 5; k++) samples[2 * k] = dequant_1bit[joined_stereo][random_dequant_index[n][k]]; } for (k = 0; k < 5; k++) samples[2 * k + 1] = SB_DITHERING_NOISE(sb,q->noise_idx); } else { for (k = 0; k < 10; k++) samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx); } run = 10; break; case 10: if (BITS_LEFT(length,gb) >= 1) { float f = 0.81; if (get_bits1(gb)) f = -f; f -= noise_samples[((sb + 1) * (j +5 * ch + 1)) & 127] * 9.0 / 40.0; samples[0] = f; } else { samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx); } run = 1; break; case 16: if (BITS_LEFT(length,gb) >= 10) { if (zero_encoding) { for (k = 0; k < 5; k++) { if ((j + k) >= 128) break; samples[k] = (get_bits1(gb) == 0) ? 0 : dequant_1bit[joined_stereo][2 * get_bits1(gb)]; } } else { n = get_bits (gb, 8); for (k = 0; k < 5; k++) samples[k] = dequant_1bit[joined_stereo][random_dequant_index[n][k]]; } } else { for (k = 0; k < 5; k++) samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx); } run = 5; break; case 24: if (BITS_LEFT(length,gb) >= 7) { n = get_bits(gb, 7); for (k = 0; k < 3; k++) samples[k] = (random_dequant_type24[n][k] - 2.0) * 0.5; } else { for (k = 0; k < 3; k++) samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx); } run = 3; break; case 30: if (BITS_LEFT(length,gb) >= 4) samples[0] = type30_dequant[qdm2_get_vlc(gb, &vlc_tab_type30, 0, 1)]; else samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx); run = 1; break; case 34: if (BITS_LEFT(length,gb) >= 7) { if (type34_first) { type34_div = (float)(1 << get_bits(gb, 2)); samples[0] = ((float)get_bits(gb, 5) - 16.0) / 15.0; type34_predictor = samples[0]; type34_first = 0; } else { samples[0] = type34_delta[qdm2_get_vlc(gb, &vlc_tab_type34, 0, 1)] / type34_div + type34_predictor; type34_predictor = samples[0]; } } else { samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx); } run = 1; break; default: samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx); run = 1; break; } if (joined_stereo) { float tmp[10][MPA_MAX_CHANNELS]; for (k = 0; k < run; k++) { tmp[k][0] = samples[k]; tmp[k][1] = (sign_bits[(j + k) / 8]) ? -samples[k] : samples[k]; } for (chs = 0; chs < q->nb_channels; chs++) for (k = 0; k < run; k++) if ((j + k) < 128) q->sb_samples[chs][j + k][sb] = q->tone_level[chs][sb][((j + k)/2)] * tmp[k][chs]; } else { for (k = 0; k < run; k++) if ((j + k) < 128) q->sb_samples[ch][j + k][sb] = q->tone_level[ch][sb][(j + k)/2] * samples[k]; } j += run; } // j loop } // channel loop } // subband loop }


_PyUnicode_DecodeUnicodeEscape(const char *s,
                               Py_ssize_t size,
                               const char *errors,
                               const char **first_invalid_escape)
{
    *first_invalid_escape = NULL;
    return PyUnicode_DecodeUnicodeEscape(s, size, errors);
}


static void lsi_do_command(LSIState *s) { SCSIDevice *dev; uint8_t buf[16]; uint32_t id; int n; DPRINTF("Send command len=%d\n", s->dbc); if (s->dbc > 16) s->dbc = 16; pci_dma_read(PCI_DEVICE(s), s->dnad, buf, s->dbc); s->sfbr = buf[0]; s->command_complete = 0; id = (s->select_tag >> 8) & 0xf; dev = scsi_device_find(&s->bus, 0, id, s->current_lun); if (!dev) { lsi_bad_selection(s, id); return; } assert(s->current == NULL); s->current = g_malloc0(sizeof(lsi_request)); s->current->tag = s->select_tag; s->current->req = scsi_req_new(dev, s->current->tag, s->current_lun, buf, s->current); n = scsi_req_enqueue(s->current->req); if (n) { if (n > 0) { lsi_set_phase(s, PHASE_DI); } else if (n < 0) { lsi_set_phase(s, PHASE_DO); } scsi_req_continue(s->current->req); } if (!s->command_complete) { if (n) { /* Command did not complete immediately so disconnect. */ lsi_add_msg_byte(s, 2); /* SAVE DATA POINTER */ lsi_add_msg_byte(s, 4); /* DISCONNECT */ /* wait data */ lsi_set_phase(s, PHASE_MI); s->msg_action = 1; lsi_queue_command(s); } else { /* wait command complete */ lsi_set_phase(s, PHASE_DI); } } }


UINT rdpgfx_read_rect16(wStream* s, RECTANGLE_16* rect16)
{
	if (Stream_GetRemainingLength(s) < 8)
	{
		WLog_ERR(TAG, "not enough data!");
		return ERROR_INVALID_DATA;
	}

	Stream_Read_UINT16(s, rect16->left);   /* left (2 bytes) */
	Stream_Read_UINT16(s, rect16->top);    /* top (2 bytes) */
	Stream_Read_UINT16(s, rect16->right);  /* right (2 bytes) */
	Stream_Read_UINT16(s, rect16->bottom); /* bottom (2 bytes) */
	return CHANNEL_RC_OK;
}


void cpu_dump_statistics (CPUState *env, FILE*f, int (*cpu_fprintf)(FILE *f, const char *fmt, ...), int flags) { #if defined(DO_PPC_STATISTICS) opc_handler_t **t1, **t2, **t3, *handler; int op1, op2, op3; t1 = env->opcodes; for (op1 = 0; op1 < 64; op1++) { handler = t1[op1]; if (is_indirect_opcode(handler)) { t2 = ind_table(handler); for (op2 = 0; op2 < 32; op2++) { handler = t2[op2]; if (is_indirect_opcode(handler)) { t3 = ind_table(handler); for (op3 = 0; op3 < 32; op3++) { handler = t3[op3]; if (handler->count == 0) continue; cpu_fprintf(f, "%02x %02x %02x (%02x %04d) %16s: " "%016" PRIx64 " %" PRId64 "\n", op1, op2, op3, op1, (op3 << 5) | op2, handler->oname, handler->count, handler->count); } } else { if (handler->count == 0) continue; cpu_fprintf(f, "%02x %02x (%02x %04d) %16s: " "%016" PRIx64 " %" PRId64 "\n", op1, op2, op1, op2, handler->oname, handler->count, handler->count); } } } else { if (handler->count == 0) continue; cpu_fprintf(f, "%02x (%02x ) %16s: %016" PRIx64 " %" PRId64 "\n", op1, op1, handler->oname, handler->count, handler->count); } } #endif }


static int dissect_spoolss_doc_info_data ( tvbuff_t * tvb , int offset , packet_info * pinfo , proto_tree * tree , dcerpc_info * di , guint8 * drep ) {
 if ( di -> conformant_run ) return offset ;
 return dissect_spoolss_doc_info_1 ( tvb , offset , pinfo , tree , di , drep ) ;
 }


ast_for_for_stmt(struct compiling *c, const node *n, int is_async)
{
    asdl_seq *_target, *seq = NULL, *suite_seq;
    expr_ty expression;
    expr_ty target, first;
    const node *node_target;
    int has_type_comment;
    string type_comment;

    if (is_async && c->c_feature_version < 5) {
        ast_error(c, n,
                "Async for loops are only supported in Python 3.5 and greater");
        return NULL;
    }

    /* for_stmt: 'for' exprlist 'in' testlist ':' [TYPE_COMMENT] suite ['else' ':' suite] */
    REQ(n, for_stmt);

    has_type_comment = TYPE(CHILD(n, 5)) == TYPE_COMMENT;

    if (NCH(n) == 9 + has_type_comment) {
        seq = ast_for_suite(c, CHILD(n, 8 + has_type_comment));
        if (!seq)
            return NULL;
    }

    node_target = CHILD(n, 1);
    _target = ast_for_exprlist(c, node_target, Store);
    if (!_target)
        return NULL;
    /* Check the # of children rather than the length of _target, since
       for x, in ... has 1 element in _target, but still requires a Tuple. */
    first = (expr_ty)asdl_seq_GET(_target, 0);
    if (NCH(node_target) == 1)
        target = first;
    else
        target = Tuple(_target, Store, first->lineno, first->col_offset, c->c_arena);

    expression = ast_for_testlist(c, CHILD(n, 3));
    if (!expression)
        return NULL;
    suite_seq = ast_for_suite(c, CHILD(n, 5 + has_type_comment));
    if (!suite_seq)
        return NULL;

    if (has_type_comment)
        type_comment = NEW_TYPE_COMMENT(CHILD(n, 5));
    else
        type_comment = NULL;

    if (is_async)
        return AsyncFor(target, expression, suite_seq, seq,
                        type_comment, LINENO(n), n->n_col_offset,
                        c->c_arena);
    else
        return For(target, expression, suite_seq, seq,
                   type_comment, LINENO(n), n->n_col_offset,
                   c->c_arena);
}


static int32_t _appendLanguageToLanguageTag ( const char * localeID , char * appendAt , int32_t capacity , UBool strict , UErrorCode * status ) {
 char buf [ ULOC_LANG_CAPACITY ] ;
 UErrorCode tmpStatus = U_ZERO_ERROR ;
 int32_t len , i ;
 int32_t reslen = 0 ;
 if ( U_FAILURE ( * status ) ) {
 return 0 ;
 }
 len = uloc_getLanguage ( localeID , buf , sizeof ( buf ) , & tmpStatus ) ;
 if ( U_FAILURE ( tmpStatus ) || tmpStatus == U_STRING_NOT_TERMINATED_WARNING ) {
 if ( strict ) {
 * status = U_ILLEGAL_ARGUMENT_ERROR ;
 return 0 ;
 }
 len = 0 ;
 }
 if ( len == 0 ) {
 if ( reslen < capacity ) {
 uprv_memcpy ( appendAt + reslen , LANG_UND , uprv_min ( LANG_UND_LEN , capacity - reslen ) ) ;
 }
 reslen += LANG_UND_LEN ;
 }
 else if ( ! _isLanguageSubtag ( buf , len ) ) {
 if ( strict ) {
 * status = U_ILLEGAL_ARGUMENT_ERROR ;
 return 0 ;
 }
 if ( reslen < capacity ) {
 uprv_memcpy ( appendAt + reslen , LANG_UND , uprv_min ( LANG_UND_LEN , capacity - reslen ) ) ;
 }
 reslen += LANG_UND_LEN ;
 }
 else {
 for ( i = 0 ;
 i < UPRV_LENGTHOF ( DEPRECATEDLANGS ) ;
 i += 2 ) {
 if ( uprv_compareInvCharsAsAscii ( buf , DEPRECATEDLANGS [ i ] ) == 0 ) {
 uprv_strcpy ( buf , DEPRECATEDLANGS [ i + 1 ] ) ;
 len = ( int32_t ) uprv_strlen ( buf ) ;
 break ;
 }
 }
 if ( reslen < capacity ) {
 uprv_memcpy ( appendAt + reslen , buf , uprv_min ( len , capacity - reslen ) ) ;
 }
 reslen += len ;
 }
 u_terminateChars ( appendAt , capacity , reslen , status ) ;
 return reslen ;
 }


_XimAttributeToValue(
    Xic			  ic,
    XIMResourceList	  res,
    CARD16		 *data,
    INT16		  data_len,
    XPointer		  value,
    BITMASK32		  mode)
{
    switch (res->resource_size) {
    case XimType_SeparatorOfNestedList:
    case XimType_NEST:
	break;

    case XimType_CARD8:
    case XimType_CARD16:
    case XimType_CARD32:
    case XimType_Window:
    case XimType_XIMHotKeyState:
	_XCopyToArg((XPointer)data, (XPointer *)&value, data_len);
	break;

    case XimType_STRING8:
	{
	    char	*str;

	    if (!(value))
		return False;

	    if (!(str = Xmalloc(data_len + 1)))
		return False;

	    (void)memcpy(str, (char *)data, data_len);
	    str[data_len] = '\0';

	    *((char **)value) = str;
	    break;
	}

    case XimType_XIMStyles:
	{
	    CARD16		 num = data[0];
	    register CARD32	*style_list = (CARD32 *)&data[2];
	    XIMStyle		*style;
	    XIMStyles		*rep;
	    register int	 i;
	    char		*p;
	    unsigned int         alloc_len;

	    if (!(value))
		return False;

	    if (num > (USHRT_MAX / sizeof(XIMStyle)))
		return False;
	    if ((sizeof(num) + (num * sizeof(XIMStyle))) > data_len)
		return False;
	    alloc_len = sizeof(XIMStyles) + sizeof(XIMStyle) * num;
	    if (alloc_len < sizeof(XIMStyles))
		return False;
	    if (!(p = Xmalloc(alloc_len)))
		return False;

	    rep   = (XIMStyles *)p;
	    style = (XIMStyle *)(p + sizeof(XIMStyles));

	    for (i = 0; i < num; i++)
		style[i] = (XIMStyle)style_list[i];

	    rep->count_styles = (unsigned short)num;
	    rep->supported_styles = style;
	    *((XIMStyles **)value) = rep;
	    break;
	}

    case XimType_XRectangle:
	{
	    XRectangle	*rep;

	    if (!(value))
		return False;

	    if (!(rep = Xmalloc(sizeof(XRectangle))))
		return False;

	    rep->x      = data[0];
	    rep->y      = data[1];
	    rep->width  = data[2];
	    rep->height = data[3];
	    *((XRectangle **)value) = rep;
	    break;
	}

    case XimType_XPoint:
	{
	    XPoint	*rep;

	    if (!(value))
		return False;

	    if (!(rep = Xmalloc(sizeof(XPoint))))
		return False;

	    rep->x = data[0];
	    rep->y = data[1];
	    *((XPoint **)value) = rep;
	    break;
	}

    case XimType_XFontSet:
	{
	    CARD16	 len = data[0];
	    char	*base_name;
	    XFontSet	 rep = (XFontSet)NULL;
	    char	**missing_list = NULL;
	    int		 missing_count;
	    char	*def_string;

	    if (!(value))
		return False;
	    if (!ic)
		return False;
	    if (len > data_len)
		return False;
	    if (!(base_name = Xmalloc(len + 1)))
		return False;

	    (void)strncpy(base_name, (char *)&data[1], (size_t)len);
	    base_name[len] = '\0';

	    if (mode & XIM_PREEDIT_ATTR) {
		if (!strcmp(base_name, ic->private.proto.preedit_font)) {
		    rep = ic->core.preedit_attr.fontset;
		} else if (!ic->private.proto.preedit_font_length) {
		    rep = XCreateFontSet(ic->core.im->core.display,
					base_name, &missing_list,
					&missing_count, &def_string);
		}
	    } else if (mode & XIM_STATUS_ATTR) {
		if (!strcmp(base_name, ic->private.proto.status_font)) {
		    rep = ic->core.status_attr.fontset;
		} else if (!ic->private.proto.status_font_length) {
		    rep = XCreateFontSet(ic->core.im->core.display,
					base_name, &missing_list,
					&missing_count, &def_string);
		}
	    }

	    Xfree(base_name);
	    Xfree(missing_list);
	    *((XFontSet *)value) = rep;
	    break;
	}

    case XimType_XIMHotKeyTriggers:
	{
	    CARD32			 num = *((CARD32 *)data);
	    register CARD32		*key_list = (CARD32 *)&data[2];
	    XIMHotKeyTrigger		*key;
	    XIMHotKeyTriggers		*rep;
	    register int		 i;
	    char			*p;
	    unsigned int		 alloc_len;

	    if (!(value))
		return False;

	    if (num > (UINT_MAX / sizeof(XIMHotKeyTrigger)))
		return False;
	    if ((sizeof(num) + (num * sizeof(XIMHotKeyTrigger))) > data_len)
		return False;
	    alloc_len = sizeof(XIMHotKeyTriggers)
		      + sizeof(XIMHotKeyTrigger) * num;
	    if (alloc_len < sizeof(XIMHotKeyTriggers))
		return False;
	    if (!(p = Xmalloc(alloc_len)))
		return False;

	    rep = (XIMHotKeyTriggers *)p;
	    key = (XIMHotKeyTrigger *)(p + sizeof(XIMHotKeyTriggers));

	    for (i = 0; i < num; i++, key_list += 3) {
		key[i].keysym        = (KeySym)key_list[0]; /* keysym */
		key[i].modifier      = (int)key_list[1];    /* modifier */
		key[i].modifier_mask = (int)key_list[2];    /* modifier_mask */
	    }

	    rep->num_hot_key = (int)num;
	    rep->key = key;
	    *((XIMHotKeyTriggers **)value) = rep;
	    break;
	}

    case XimType_XIMStringConversion:
	{
	    break;
	}

    default:
	return False;
    }
    return True;
}


static int get_cluster_offset(BlockDriverState *bs, VmdkExtent *extent, VmdkMetaData *m_data, uint64_t offset, bool allocate, uint64_t *cluster_offset, uint64_t skip_start_bytes, uint64_t skip_end_bytes) { unsigned int l1_index, l2_offset, l2_index; int min_index, i, j; uint32_t min_count, *l2_table; bool zeroed = false; int64_t ret; int64_t cluster_sector; if (m_data) { m_data->valid = 0; } if (extent->flat) { *cluster_offset = extent->flat_start_offset; return VMDK_OK; } offset -= (extent->end_sector - extent->sectors) * SECTOR_SIZE; l1_index = (offset >> 9) / extent->l1_entry_sectors; if (l1_index >= extent->l1_size) { return VMDK_ERROR; } l2_offset = extent->l1_table[l1_index]; if (!l2_offset) { return VMDK_UNALLOC; } for (i = 0; i < L2_CACHE_SIZE; i++) { if (l2_offset == extent->l2_cache_offsets[i]) { /* increment the hit count */ if (++extent->l2_cache_counts[i] == 0xffffffff) { for (j = 0; j < L2_CACHE_SIZE; j++) { extent->l2_cache_counts[j] >>= 1; } } l2_table = extent->l2_cache + (i * extent->l2_size); goto found; } } /* not found: load a new entry in the least used one */ min_index = 0; min_count = 0xffffffff; for (i = 0; i < L2_CACHE_SIZE; i++) { if (extent->l2_cache_counts[i] < min_count) { min_count = extent->l2_cache_counts[i]; min_index = i; } } l2_table = extent->l2_cache + (min_index * extent->l2_size); if (bdrv_pread(extent->file, (int64_t)l2_offset * 512, l2_table, extent->l2_size * sizeof(uint32_t) ) != extent->l2_size * sizeof(uint32_t)) { return VMDK_ERROR; } extent->l2_cache_offsets[min_index] = l2_offset; extent->l2_cache_counts[min_index] = 1; found: l2_index = ((offset >> 9) / extent->cluster_sectors) % extent->l2_size; cluster_sector = le32_to_cpu(l2_table[l2_index]); if (m_data) { m_data->valid = 1; m_data->l1_index = l1_index; m_data->l2_index = l2_index; m_data->l2_offset = l2_offset; m_data->l2_cache_entry = &l2_table[l2_index]; } if (extent->has_zero_grain && cluster_sector == VMDK_GTE_ZEROED) { zeroed = true; } if (!cluster_sector || zeroed) { if (!allocate) { return zeroed ? VMDK_ZEROED : VMDK_UNALLOC; } cluster_sector = extent->next_cluster_sector; extent->next_cluster_sector += extent->cluster_sectors; /* First of all we write grain itself, to avoid race condition * that may to corrupt the image. * This problem may occur because of insufficient space on host disk * or inappropriate VM shutdown. */ ret = get_whole_cluster(bs, extent, cluster_sector * BDRV_SECTOR_SIZE, offset, skip_start_bytes, skip_end_bytes); if (ret) { return ret; } } *cluster_offset = cluster_sector << BDRV_SECTOR_BITS; return VMDK_OK; }


static int blk_init(struct XenDevice *xendev) { struct XenBlkDev *blkdev = container_of(xendev, struct XenBlkDev, xendev); int index, qflags, have_barriers, info = 0; char *h; /* read xenstore entries */ if (blkdev->params == NULL) { blkdev->params = xenstore_read_be_str(&blkdev->xendev, "params"); h = strchr(blkdev->params, ':'); if (h != NULL) { blkdev->fileproto = blkdev->params; blkdev->filename = h+1; *h = 0; } else { blkdev->fileproto = "<unset>"; blkdev->filename = blkdev->params; } } if (blkdev->mode == NULL) blkdev->mode = xenstore_read_be_str(&blkdev->xendev, "mode"); if (blkdev->type == NULL) blkdev->type = xenstore_read_be_str(&blkdev->xendev, "type"); if (blkdev->dev == NULL) blkdev->dev = xenstore_read_be_str(&blkdev->xendev, "dev"); if (blkdev->devtype == NULL) blkdev->devtype = xenstore_read_be_str(&blkdev->xendev, "device-type"); /* do we have all we need? */ if (blkdev->params == NULL || blkdev->mode == NULL || blkdev->type == NULL || blkdev->dev == NULL) return -1; /* read-only ? */ if (strcmp(blkdev->mode, "w") == 0) { qflags = BDRV_O_RDWR; } else { qflags = 0; info |= VDISK_READONLY; } /* cdrom ? */ if (blkdev->devtype && !strcmp(blkdev->devtype, "cdrom")) info |= VDISK_CDROM; /* init qemu block driver */ index = (blkdev->xendev.dev - 202 * 256) / 16; blkdev->dinfo = drive_get(IF_XEN, 0, index); if (!blkdev->dinfo) { /* setup via xenbus -> create new block driver instance */ xen_be_printf(&blkdev->xendev, 2, "create new bdrv (xenbus setup)\n"); blkdev->bs = bdrv_new(blkdev->dev); if (blkdev->bs) { if (bdrv_open(blkdev->bs, blkdev->filename, qflags, bdrv_find_whitelisted_format(blkdev->fileproto)) != 0) { bdrv_delete(blkdev->bs); blkdev->bs = NULL; } } if (!blkdev->bs) return -1; } else { /* setup via qemu cmdline -> already setup for us */ xen_be_printf(&blkdev->xendev, 2, "get configured bdrv (cmdline setup)\n"); blkdev->bs = blkdev->dinfo->bdrv; } blkdev->file_blk = BLOCK_SIZE; blkdev->file_size = bdrv_getlength(blkdev->bs); if (blkdev->file_size < 0) { xen_be_printf(&blkdev->xendev, 1, "bdrv_getlength: %d (%s) | drv %s\n", (int)blkdev->file_size, strerror(-blkdev->file_size), blkdev->bs->drv ? blkdev->bs->drv->format_name : "-"); blkdev->file_size = 0; } have_barriers = blkdev->bs->drv && blkdev->bs->drv->bdrv_flush ? 1 : 0; xen_be_printf(xendev, 1, "type \"%s\", fileproto \"%s\", filename \"%s\"," " size %" PRId64 " (%" PRId64 " MB)\n", blkdev->type, blkdev->fileproto, blkdev->filename, blkdev->file_size, blkdev->file_size >> 20); /* fill info */ xenstore_write_be_int(&blkdev->xendev, "feature-barrier", have_barriers); xenstore_write_be_int(&blkdev->xendev, "info", info); xenstore_write_be_int(&blkdev->xendev, "sector-size", blkdev->file_blk); xenstore_write_be_int(&blkdev->xendev, "sectors", blkdev->file_size / blkdev->file_blk); return 0; }


init_normalization(struct compiling *c)
{
    PyObject *m = PyImport_ImportModuleNoBlock("unicodedata");
    if (!m)
        return 0;
    c->c_normalize = PyObject_GetAttrString(m, "normalize");
    Py_DECREF(m);
    if (!c->c_normalize)
        return 0;
    c->c_normalize_args = Py_BuildValue("(sN)", "NFKC", Py_None);
    if (!c->c_normalize_args) {
        Py_CLEAR(c->c_normalize);
        return 0;
    }
    PyTuple_SET_ITEM(c->c_normalize_args, 1, NULL);
    return 1;
}


static void smc91c111_receive(void *opaque, const uint8_t *buf, size_t size) { smc91c111_state *s = (smc91c111_state *)opaque; int status; int packetsize; uint32_t crc; int packetnum; uint8_t *p; if ((s->rcr & RCR_RXEN) == 0 || (s->rcr & RCR_SOFT_RST)) return; /* Short packets are padded with zeros. Receiving a packet < 64 bytes long is considered an error condition. */ if (size < 64) packetsize = 64; else packetsize = (size & ~1); packetsize += 6; crc = (s->rcr & RCR_STRIP_CRC) == 0; if (crc) packetsize += 4; /* TODO: Flag overrun and receive errors. */ if (packetsize > 2048) return; packetnum = smc91c111_allocate_packet(s); if (packetnum == 0x80) return; s->rx_fifo[s->rx_fifo_len++] = packetnum; p = &s->data[packetnum][0]; /* ??? Multicast packets? */ status = 0; if (size > 1518) status |= RS_TOOLONG; if (size & 1) status |= RS_ODDFRAME; *(p++) = status & 0xff; *(p++) = status >> 8; *(p++) = packetsize & 0xff; *(p++) = packetsize >> 8; memcpy(p, buf, size & ~1); p += (size & ~1); /* Pad short packets. */ if (size < 64) { int pad; if (size & 1) *(p++) = buf[size - 1]; pad = 64 - size; memset(p, 0, pad); p += pad; size = 64; } /* It's not clear if the CRC should go before or after the last byte in odd sized packets. Linux disables the CRC, so that's no help. The pictures in the documentation show the CRC aligned on a 16-bit boundary before the last odd byte, so that's what we do. */ if (crc) { crc = crc32(~0, buf, size); *(p++) = crc & 0xff; crc >>= 8; *(p++) = crc & 0xff; crc >>= 8; *(p++) = crc & 0xff; crc >>= 8; *(p++) = crc & 0xff; crc >>= 8; } if (size & 1) { *(p++) = buf[size - 1]; *(p++) = 0x60; } else { *(p++) = 0; *(p++) = 0x40; } /* TODO: Raise early RX interrupt? */ s->int_level |= INT_RCV; smc91c111_update(s); }


int ssh_buffer_add_data(struct ssh_buffer_struct *buffer, const void *data, uint32_t len)
{
  buffer_verify(buffer);

  if (data == NULL) {
      return -1;
  }

  if (buffer->used + len < len) {
    return -1;
  }

  if (buffer->allocated < (buffer->used + len)) {
    if(buffer->pos > 0)
      buffer_shift(buffer);
    if (realloc_buffer(buffer, buffer->used + len) < 0) {
      return -1;
    }
  }

  memcpy(buffer->data+buffer->used, data, len);
  buffer->used+=len;
  buffer_verify(buffer);
  return 0;
}


static int mov_read_default(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom) { int64_t total_size = 0; MOV_atom_t a; int i; int err = 0; a.offset = atom.offset; if (atom.size < 0) atom.size = INT64_MAX; while(((total_size + 8) < atom.size) && !url_feof(pb) && !err) { a.size = atom.size; a.type=0L; if(atom.size >= 8) { a.size = get_be32(pb); a.type = get_le32(pb); } total_size += 8; a.offset += 8; dprintf(c->fc, "type: %08x %.4s sz: %"PRIx64" %"PRIx64" %"PRIx64"\n", a.type, (char*)&a.type, a.size, atom.size, total_size); if (a.size == 1) { /* 64 bit extended size */ a.size = get_be64(pb) - 8; a.offset += 8; total_size += 8; } if (a.size == 0) { a.size = atom.size - total_size; if (a.size <= 8) break; } a.size -= 8; if(a.size < 0 || a.size > atom.size - total_size) break; for (i = 0; c->parse_table[i].type != 0L && c->parse_table[i].type != a.type; i++) /* empty */; if (c->parse_table[i].type == 0) { /* skip leaf atoms data */ url_fskip(pb, a.size); } else { offset_t start_pos = url_ftell(pb); int64_t left; err = (c->parse_table[i].func)(c, pb, a); left = a.size - url_ftell(pb) + start_pos; if (left > 0) /* skip garbage at atom end */ url_fskip(pb, left); } a.offset += a.size; total_size += a.size; } if (!err && total_size < atom.size && atom.size < 0x7ffff) { url_fskip(pb, atom.size - total_size); } return err; }


handle_keywordonly_args(struct compiling *c, const node *n, int start,
                        asdl_seq *kwonlyargs, asdl_seq *kwdefaults)
{
    PyObject *argname;
    node *ch;
    expr_ty expression, annotation;
    arg_ty arg = NULL;
    int i = start;
    int j = 0; /* index for kwdefaults and kwonlyargs */

    if (kwonlyargs == NULL) {
        ast_error(c, CHILD(n, start), "named arguments must follow bare *");
        return -1;
    }
    assert(kwdefaults != NULL);
    while (i < NCH(n)) {
        ch = CHILD(n, i);
        switch (TYPE(ch)) {
            case vfpdef:
            case tfpdef:
                if (i + 1 < NCH(n) && TYPE(CHILD(n, i + 1)) == EQUAL) {
                    expression = ast_for_expr(c, CHILD(n, i + 2));
                    if (!expression)
                        goto error;
                    asdl_seq_SET(kwdefaults, j, expression);
                    i += 2; /* '=' and test */
                }
                else { /* setting NULL if no default value exists */
                    asdl_seq_SET(kwdefaults, j, NULL);
                }
                if (NCH(ch) == 3) {
                    /* ch is NAME ':' test */
                    annotation = ast_for_expr(c, CHILD(ch, 2));
                    if (!annotation)
                        goto error;
                }
                else {
                    annotation = NULL;
                }
                ch = CHILD(ch, 0);
                argname = NEW_IDENTIFIER(ch);
                if (!argname)
                    goto error;
                if (forbidden_name(c, argname, ch, 0))
                    goto error;
                arg = arg(argname, annotation, NULL, LINENO(ch), ch->n_col_offset,
                          c->c_arena);
                if (!arg)
                    goto error;
                asdl_seq_SET(kwonlyargs, j++, arg);
                i += 1; /* the name */
                if (TYPE(CHILD(n, i)) == COMMA)
                    i += 1; /* the comma, if present */
                break;
            case TYPE_COMMENT:
                /* arg will be equal to the last argument processed */
                arg->type_comment = NEW_TYPE_COMMENT(ch);
                if (!arg->type_comment)
                    goto error;
                i += 1;
                break;
            case DOUBLESTAR:
                return i;
            default:
                ast_error(c, ch, "unexpected node");
                goto error;
        }
    }
    return i;
 error:
    return -1;
}


handle_keywordonly_args(struct compiling *c, const node *n, int start,
                        asdl_seq *kwonlyargs, asdl_seq *kwdefaults)
{
    PyObject *argname;
    node *ch;
    expr_ty expression, annotation;
    arg_ty arg = NULL;
    int i = start;
    int j = 0; /* index for kwdefaults and kwonlyargs */

    if (kwonlyargs == NULL) {
        ast_error(c, CHILD(n, start), "named arguments must follow bare *");
        return -1;
    }
    assert(kwdefaults != NULL);
    while (i < NCH(n)) {
        ch = CHILD(n, i);
        switch (TYPE(ch)) {
            case vfpdef:
            case tfpdef:
                if (i + 1 < NCH(n) && TYPE(CHILD(n, i + 1)) == EQUAL) {
                    expression = ast_for_expr(c, CHILD(n, i + 2));
                    if (!expression)
                        goto error;
                    asdl_seq_SET(kwdefaults, j, expression);
                    i += 2; /* '=' and test */
                }
                else { /* setting NULL if no default value exists */
                    asdl_seq_SET(kwdefaults, j, NULL);
                }
                if (NCH(ch) == 3) {
                    /* ch is NAME ':' test */
                    annotation = ast_for_expr(c, CHILD(ch, 2));
                    if (!annotation)
                        goto error;
                }
                else {
                    annotation = NULL;
                }
                ch = CHILD(ch, 0);
                argname = NEW_IDENTIFIER(ch);
                if (!argname)
                    goto error;
                if (forbidden_name(c, argname, ch, 0))
                    goto error;
                arg = arg(argname, annotation, NULL, LINENO(ch), ch->n_col_offset,
                          c->c_arena);
                if (!arg)
                    goto error;
                asdl_seq_SET(kwonlyargs, j++, arg);
                i += 1; /* the name */
                if (i < NCH(n) && TYPE(CHILD(n, i)) == COMMA)
                    i += 1; /* the comma, if present */
                break;
            case TYPE_COMMENT:
                /* arg will be equal to the last argument processed */
                arg->type_comment = NEW_TYPE_COMMENT(ch);
                if (!arg->type_comment)
                    goto error;
                i += 1;
                break;
            case DOUBLESTAR:
                return i;
            default:
                ast_error(c, ch, "unexpected node");
                goto error;
        }
    }
    return i;
 error:
    return -1;
}


void dsputil_init_armv4l(DSPContext* c, AVCodecContext *avctx) { const int idct_algo= avctx->idct_algo; ff_put_pixels_clamped = c->put_pixels_clamped; ff_add_pixels_clamped = c->add_pixels_clamped; if(idct_algo==FF_IDCT_ARM){ if(idct_algo==FF_IDCT_AUTO || idct_algo==FF_IDCT_ARM){ c->idct_put= j_rev_dct_ARM_put; c->idct_add= j_rev_dct_ARM_add; c->idct = j_rev_dct_ARM; c->idct_permutation_type= FF_LIBMPEG2_IDCT_PERM;/* FF_NO_IDCT_PERM */ } else if (idct_algo==FF_IDCT_SIMPLEARM){ c->idct_put= simple_idct_ARM_put; c->idct_add= simple_idct_ARM_add; c->idct = simple_idct_ARM; } }


static void dissect_coap_opt_ctype ( tvbuff_t * tvb , proto_item * head_item , proto_tree * subtree , gint offset , gint opt_length , int hf , coap_info * coinfo ) {
 if ( opt_length == 0 ) {
 coinfo -> ctype_value = 0 ;
 }
 else {
 coinfo -> ctype_value = coap_get_opt_uint ( tvb , offset , opt_length ) ;
 }
 coinfo -> ctype_str = val_to_str ( coinfo -> ctype_value , vals_ctype , "Unknown Type %u" ) ;
 proto_tree_add_string ( subtree , hf , tvb , offset , opt_length , coinfo -> ctype_str ) ;
 proto_item_append_text ( head_item , ": %s" , coinfo -> ctype_str ) ;
 }


_mibindex_add( const char *dirname, int i )
{
    const int old_mibindex_max = _mibindex_max;

    DEBUGMSGTL(("mibindex", "add: %s (%d)\n", dirname, i ));
    if ( i == -1 )
        i = _mibindex++;
    if ( i >= _mibindex_max ) {
        /*
         * If the index array is full (or non-existent)
         *   then expand (or create) it
         */
        _mibindex_max = i + 10;
        _mibindexes = realloc(_mibindexes,
                              _mibindex_max * sizeof(_mibindexes[0]));
        netsnmp_assert(_mibindexes);
        memset(_mibindexes + old_mibindex_max, 0,
               (_mibindex_max - old_mibindex_max) * sizeof(_mibindexes[0]));
    }

    _mibindexes[ i ] = strdup( dirname );
    if ( i >= _mibindex )
        _mibindex = i+1;

    DEBUGMSGTL(("mibindex", "add: %d/%d/%d\n", i, _mibindex, _mibindex_max ));
    return i;
}


static int rac_get_model_sym ( RangeCoder * c , Model * m ) {
 int prob , prob2 , helper , val ;
 int end , end2 ;
 prob = 0 ;
 prob2 = c -> range ;
 c -> range >>= MODEL_SCALE ;
 val = 0 ;
 end = m -> num_syms >> 1 ;
 end2 = m -> num_syms ;
 do {
 helper = m -> freqs [ end ] * c -> range ;
 if ( helper <= c -> low ) {
 val = end ;
 prob = helper ;
 }
 else {
 end2 = end ;
 prob2 = helper ;
 }
 end = ( end2 + val ) >> 1 ;
 }
 while ( end != val ) ;
 c -> low -= prob ;
 c -> range = prob2 - prob ;
 if ( c -> range < RAC_BOTTOM ) rac_normalise ( c ) ;
 model_update ( m , val ) ;
 return val ;
 }


netsnmp_mibindex_load( void )
{
    DIR *dir;
    struct dirent *file;
    FILE *fp;
    char tmpbuf[ 300];
    char tmpbuf2[300];
    int  i;
    char *cp;

    /*
     * Open the MIB index directory, or create it (empty)
     */
    snprintf( tmpbuf, sizeof(tmpbuf), "%s/mib_indexes",
              get_persistent_directory());
    tmpbuf[sizeof(tmpbuf)-1] = 0;
    dir = opendir( tmpbuf );
    if ( dir == NULL ) {
        DEBUGMSGTL(("mibindex", "load: (new)\n"));
        mkdirhier( tmpbuf, NETSNMP_AGENT_DIRECTORY_MODE, 0);
        return;
    }

    /*
     * Create a list of which directory each file refers to
     */
    while ((file = readdir( dir ))) {
        if ( !isdigit((unsigned char)(file->d_name[0])))
            continue;
        i = atoi( file->d_name );

        snprintf( tmpbuf, sizeof(tmpbuf), "%s/mib_indexes/%d",
              get_persistent_directory(), i );
        tmpbuf[sizeof(tmpbuf)-1] = 0;
        fp = fopen( tmpbuf, "r" );
        if (!fp)
            continue;
        cp = fgets( tmpbuf2, sizeof(tmpbuf2), fp );
        fclose( fp );
        if ( !cp ) {
            DEBUGMSGTL(("mibindex", "Empty MIB index (%d)\n", i));
            continue;
        }
        if ( strncmp( tmpbuf2, "DIR ", 4 ) != 0 ) {
            DEBUGMSGTL(("mibindex", "Malformed MIB index (%d)\n", i));
            continue;
        }
        tmpbuf2[strlen(tmpbuf2)-1] = 0;
        DEBUGMSGTL(("mibindex", "load: (%d) %s\n", i, tmpbuf2));
        (void)_mibindex_add( tmpbuf2+4, i );  /* Skip 'DIR ' */
    }
    closedir( dir );
}


static void free_test_data(test_data *data) { AcpiSdtTable *temp; int i; if (data->rsdt_tables_addr) { g_free(data->rsdt_tables_addr); } for (i = 0; i < data->tables->len; ++i) { temp = &g_array_index(data->tables, AcpiSdtTable, i); if (temp->aml) { g_free(temp->aml); } if (temp->aml_file) { if (!temp->tmp_files_retain && g_strstr_len(temp->aml_file, -1, "aml-")) { unlink(temp->aml_file); } g_free(temp->aml_file); } if (temp->asl) { g_free(temp->asl); } if (temp->asl_file) { if (!temp->tmp_files_retain) { unlink(temp->asl_file); } g_free(temp->asl_file); } } g_array_free(data->tables, false); }


static inline uint64_t vtd_iova_limit(VTDContextEntry *ce) { uint32_t ce_agaw = vtd_ce_get_agaw(ce); return 1ULL << MIN(ce_agaw, VTD_MGAW); }


static void unpack_roq_qcell ( uint8_t cb2 [ ] , roq_qcell * qcell , uint8_t u [ 4 * 4 * 3 ] ) {
 int i , cp ;
 static const int offsets [ 4 ] = {
 0 , 2 , 8 , 10 }
 ;
 for ( cp = 0 ;
 cp < 3 ;
 cp ++ ) for ( i = 0 ;
 i < 4 ;
 i ++ ) {
 u [ 4 * 4 * cp + offsets [ i ] ] = cb2 [ qcell -> idx [ i ] * 2 * 2 * 3 + 4 * cp ] ;
 u [ 4 * 4 * cp + offsets [ i ] + 1 ] = cb2 [ qcell -> idx [ i ] * 2 * 2 * 3 + 4 * cp + 1 ] ;
 u [ 4 * 4 * cp + offsets [ i ] + 4 ] = cb2 [ qcell -> idx [ i ] * 2 * 2 * 3 + 4 * cp + 2 ] ;
 u [ 4 * 4 * cp + offsets [ i ] + 5 ] = cb2 [ qcell -> idx [ i ] * 2 * 2 * 3 + 4 * cp + 3 ] ;
 }
 }


static afs_int32 WhoIsThisWithName ( struct rx_call * acall , struct ubik_trans * at , afs_int32 * aid , char * aname ) {
 struct rx_connection * tconn ;
 afs_int32 code ;
 char tcell [ MAXKTCREALMLEN ] ;
 char name [ MAXKTCNAMELEN ] ;
 char inst [ MAXKTCNAMELEN ] ;
 int ilen ;
 char vname [ 256 ] ;
 * aid = ANONYMOUSID ;
 tconn = rx_ConnectionOf ( acall ) ;
 code = rx_SecurityClassOf ( tconn ) ;
 if ( code == 0 ) return 0 ;
 else if ( code == 1 ) {
 goto done ;
 }
 else if ( code == 2 ) {
 int clen ;
 if ( ( code = rxkad_GetServerInfo ( acall -> conn , NULL , 0 , name , inst , tcell , NULL ) ) ) goto done ;
 strncpy ( vname , name , sizeof ( vname ) ) ;
 if ( ( ilen = strlen ( inst ) ) ) {
 if ( strlen ( vname ) + 1 + ilen >= sizeof ( vname ) ) goto done ;
 strcat ( vname , "." ) ;
 strcat ( vname , inst ) ;
 }
 if ( ( clen = strlen ( tcell ) ) ) {
 int foreign = afs_is_foreign_ticket_name ( name , inst , tcell , pr_realmName ) ;
 if ( foreign ) {
 if ( strlen ( vname ) + 1 + clen >= sizeof ( vname ) ) goto done ;
 strcat ( vname , "@" ) ;
 strcat ( vname , tcell ) ;
 lcstring ( vname , vname , sizeof ( vname ) ) ;
 code = NameToID ( at , vname , aid ) ;
 strcpy ( aname , vname ) ;
 return 2 ;
 }
 }
 if ( strcmp ( AUTH_SUPERUSER , vname ) == 0 ) * aid = SYSADMINID ;
 else {
 lcstring ( vname , vname , sizeof ( vname ) ) ;
 code = NameToID ( at , vname , aid ) ;
 }
 }
 done : if ( code && ! pr_noAuth ) return - 1 ;
 return 0 ;
 }


usm_malloc_usmStateReference(void)
{
    struct usmStateReference *retval = (struct usmStateReference *)
        calloc(1, sizeof(struct usmStateReference));

    return retval;
}                               /* end usm_malloc_usmStateReference() */


static av_cold int raw_init_decoder(AVCodecContext *avctx) { RawVideoContext *context = avctx->priv_data; const AVPixFmtDescriptor *desc; ff_bswapdsp_init(&context->bbdsp); if ( avctx->codec_tag == MKTAG('r','a','w',' ') || avctx->codec_tag == MKTAG('N','O','1','6')) avctx->pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov, avctx->bits_per_coded_sample); else if (avctx->codec_tag == MKTAG('W', 'R', 'A', 'W')) avctx->pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_avi, avctx->bits_per_coded_sample); else if (avctx->codec_tag && (avctx->codec_tag & 0xFFFFFF) != MKTAG('B','I','T', 0)) avctx->pix_fmt = avpriv_find_pix_fmt(ff_raw_pix_fmt_tags, avctx->codec_tag); else if (avctx->pix_fmt == AV_PIX_FMT_NONE && avctx->bits_per_coded_sample) avctx->pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_avi, avctx->bits_per_coded_sample); desc = av_pix_fmt_desc_get(avctx->pix_fmt); if (!desc) { av_log(avctx, AV_LOG_ERROR, "Invalid pixel format.\n"); return AVERROR(EINVAL); } if (desc->flags & (AV_PIX_FMT_FLAG_PAL | AV_PIX_FMT_FLAG_PSEUDOPAL)) { context->palette = av_buffer_alloc(AVPALETTE_SIZE); if (!context->palette) return AVERROR(ENOMEM); if (desc->flags & AV_PIX_FMT_FLAG_PSEUDOPAL) avpriv_set_systematic_pal2((uint32_t*)context->palette->data, avctx->pix_fmt); else memset(context->palette->data, 0, AVPALETTE_SIZE); } if ((avctx->extradata_size >= 9 && !memcmp(avctx->extradata + avctx->extradata_size - 9, "BottomUp", 9)) || avctx->codec_tag == MKTAG('c','y','u','v') || avctx->codec_tag == MKTAG(3, 0, 0, 0) || avctx->codec_tag == MKTAG('W','R','A','W')) context->flip = 1; if (avctx->codec_tag == AV_RL32("yuv2") && avctx->pix_fmt == AV_PIX_FMT_YUYV422) context->is_yuv2 = 1; return 0; }


fixExec2Error(int action,
             u_char * var_val,
             u_char var_val_type,
             size_t var_val_len,
             u_char * statP, oid * name, size_t name_len)
{
    netsnmp_old_extend *exten = NULL;
    unsigned int idx;

    idx = name[name_len-1] -1;
    exten = &compatability_entries[ idx ];

#ifndef NETSNMP_NO_WRITE_SUPPORT
    switch (action) {
    case MODE_SET_RESERVE1:
        if (var_val_type != ASN_INTEGER) {
            snmp_log(LOG_ERR, "Wrong type != int\n");
            return SNMP_ERR_WRONGTYPE;
        }
        idx = *((long *) var_val);
        if (idx != 1) {
            snmp_log(LOG_ERR, "Wrong value != 1\n");
            return SNMP_ERR_WRONGVALUE;
        }
        if (!exten || !exten->efix_entry) {
            snmp_log(LOG_ERR, "No command to run\n");
            return SNMP_ERR_GENERR;
        }
        return SNMP_ERR_NOERROR;

    case MODE_SET_COMMIT:
        netsnmp_cache_check_and_reload( exten->efix_entry->cache );
    }
#endif /* !NETSNMP_NO_WRITE_SUPPORT */
    return SNMP_ERR_NOERROR;
}


static PHP_NAMED_FUNCTION ( zif_zip_entry_compressedsize ) {
 php_zip_entry_get_info ( INTERNAL_FUNCTION_PARAM_PASSTHRU , 1 ) ;
 }


static void event_notifier_ready(EventNotifier *notifier) { ThreadPool *pool = container_of(notifier, ThreadPool, notifier); ThreadPoolElement *elem, *next; event_notifier_test_and_clear(notifier); restart: QLIST_FOREACH_SAFE(elem, &pool->head, all, next) { if (elem->state != THREAD_CANCELED && elem->state != THREAD_DONE) { continue; } if (elem->state == THREAD_DONE) { trace_thread_pool_complete(pool, elem, elem->common.opaque, elem->ret); } if (elem->state == THREAD_DONE && elem->common.cb) { QLIST_REMOVE(elem, all); /* Read state before ret. */ smp_rmb(); elem->common.cb(elem->common.opaque, elem->ret); qemu_aio_release(elem); goto restart; } else { /* remove the request */ QLIST_REMOVE(elem, all); qemu_aio_release(elem); } } }


pkcs11rsa_fromlabel(dst_key_t *key, const char *engine, const char *label,
		    const char *pin)
{
	CK_RV rv;
	CK_OBJECT_HANDLE hKey = CK_INVALID_HANDLE;
	CK_OBJECT_CLASS keyClass = CKO_PUBLIC_KEY;
	CK_KEY_TYPE keyType = CKK_RSA;
	CK_ATTRIBUTE searchTemplate[] =
	{
		{ CKA_CLASS, &keyClass, (CK_ULONG) sizeof(keyClass) },
		{ CKA_KEY_TYPE, &keyType, (CK_ULONG) sizeof(keyType) },
		{ CKA_TOKEN, &truevalue, (CK_ULONG) sizeof(truevalue) },
		{ CKA_LABEL, NULL, 0 }
	};
	CK_ULONG cnt;
	CK_ATTRIBUTE *attr;
	pk11_object_t *rsa;
	pk11_context_t *pk11_ctx = NULL;
	isc_result_t ret;
	unsigned int i;

	UNUSED(pin);

	rsa = (pk11_object_t *) isc_mem_get(key->mctx, sizeof(*rsa));
	if (rsa == NULL)
		return (ISC_R_NOMEMORY);
	memset(rsa, 0, sizeof(*rsa));
	rsa->object = CK_INVALID_HANDLE;
	rsa->ontoken = true;
	rsa->reqlogon = true;
	key->keydata.pkey = rsa;

	rsa->repr = (CK_ATTRIBUTE *) isc_mem_get(key->mctx, sizeof(*attr) * 2);
	if (rsa->repr == NULL)
		DST_RET(ISC_R_NOMEMORY);
	memset(rsa->repr, 0, sizeof(*attr) * 2);
	rsa->attrcnt = 2;
	attr = rsa->repr;
	attr[0].type = CKA_MODULUS;
	attr[1].type = CKA_PUBLIC_EXPONENT;

	ret = pk11_parse_uri(rsa, label, key->mctx, OP_RSA);
	if (ret != ISC_R_SUCCESS)
		goto err;

	pk11_ctx = (pk11_context_t *) isc_mem_get(key->mctx,
						  sizeof(*pk11_ctx));
	if (pk11_ctx == NULL)
		DST_RET(ISC_R_NOMEMORY);
	ret = pk11_get_session(pk11_ctx, OP_RSA, true, false,
			       rsa->reqlogon, NULL, rsa->slot);
	if (ret != ISC_R_SUCCESS)
		goto err;

	attr = pk11_attribute_bytype(rsa, CKA_LABEL);
	if (attr == NULL) {
		attr = pk11_attribute_bytype(rsa, CKA_ID);
		INSIST(attr != NULL);
		searchTemplate[3].type = CKA_ID;
	}
	searchTemplate[3].pValue = attr->pValue;
	searchTemplate[3].ulValueLen = attr->ulValueLen;

	PK11_RET(pkcs_C_FindObjectsInit,
		 (pk11_ctx->session, searchTemplate, (CK_ULONG) 4),
		 DST_R_CRYPTOFAILURE);
	PK11_RET(pkcs_C_FindObjects,
		 (pk11_ctx->session, &hKey, (CK_ULONG) 1, &cnt),
		 DST_R_CRYPTOFAILURE);
	(void) pkcs_C_FindObjectsFinal(pk11_ctx->session);
	if (cnt == 0)
		DST_RET(ISC_R_NOTFOUND);
	if (cnt > 1)
		DST_RET(ISC_R_EXISTS);

	attr = rsa->repr;
	PK11_RET(pkcs_C_GetAttributeValue,
		 (pk11_ctx->session, hKey, attr, 2),
		 DST_R_CRYPTOFAILURE);
	for (i = 0; i <= 1; i++) {
		attr[i].pValue = isc_mem_get(key->mctx, attr[i].ulValueLen);
		if (attr[i].pValue == NULL)
			DST_RET(ISC_R_NOMEMORY);
		memset(attr[i].pValue, 0, attr[i].ulValueLen);
	}
	PK11_RET(pkcs_C_GetAttributeValue,
		 (pk11_ctx->session, hKey, attr, 2),
		 DST_R_CRYPTOFAILURE);

	keyClass = CKO_PRIVATE_KEY;
	PK11_RET(pkcs_C_FindObjectsInit,
		 (pk11_ctx->session, searchTemplate, (CK_ULONG) 4),
		 DST_R_CRYPTOFAILURE);
	PK11_RET(pkcs_C_FindObjects,
		 (pk11_ctx->session, &rsa->object, (CK_ULONG) 1, &cnt),
		 DST_R_CRYPTOFAILURE);
	(void) pkcs_C_FindObjectsFinal(pk11_ctx->session);
	if (cnt == 0)
		DST_RET(ISC_R_NOTFOUND);
	if (cnt > 1)
		DST_RET(ISC_R_EXISTS);

	if (engine != NULL) {
		key->engine = isc_mem_strdup(key->mctx, engine);
		if (key->engine == NULL)
			DST_RET(ISC_R_NOMEMORY);
	}

	key->label = isc_mem_strdup(key->mctx, label);
	if (key->label == NULL)
		DST_RET(ISC_R_NOMEMORY);

	attr = pk11_attribute_bytype(rsa, CKA_PUBLIC_EXPONENT);
	INSIST(attr != NULL);
	if (pk11_numbits(attr->pValue, attr->ulValueLen) > RSA_MAX_PUBEXP_BITS)
		DST_RET(ISC_R_RANGE);

	attr = pk11_attribute_bytype(rsa, CKA_MODULUS);
	INSIST(attr != NULL);
	key->key_size = pk11_numbits(attr->pValue, attr->ulValueLen);

	pk11_return_session(pk11_ctx);
	isc_safe_memwipe(pk11_ctx, sizeof(*pk11_ctx));
	isc_mem_put(key->mctx, pk11_ctx, sizeof(*pk11_ctx));

	return (ISC_R_SUCCESS);

    err:
	pkcs11rsa_destroy(key);
	if (pk11_ctx != NULL) {
		pk11_return_session(pk11_ctx);
		isc_safe_memwipe(pk11_ctx, sizeof(*pk11_ctx));
		isc_mem_put(key->mctx, pk11_ctx, sizeof(*pk11_ctx));
	}

	return (ret);
}


static int scsi_block_initfn(SCSIDevice *dev) { SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev); int sg_version; int rc; if (!s->qdev.conf.bs) { error_report("drive property not set"); return -1; } /* check we are using a driver managing SG_IO (version 3 and after) */ rc = bdrv_ioctl(s->qdev.conf.bs, SG_GET_VERSION_NUM, &sg_version); if (rc < 0) { error_report("cannot get SG_IO version number: %s. " "Is this a SCSI device?", strerror(-rc)); return -1; } if (sg_version < 30000) { error_report("scsi generic interface too old"); return -1; } /* get device type from INQUIRY data */ rc = get_device_type(s); if (rc < 0) { error_report("INQUIRY failed"); return -1; } /* Make a guess for the block size, we'll fix it when the guest sends. * READ CAPACITY. If they don't, they likely would assume these sizes * anyway. (TODO: check in /sys). */ if (s->qdev.type == TYPE_ROM || s->qdev.type == TYPE_WORM) { s->qdev.blocksize = 2048; } else { s->qdev.blocksize = 512; } /* Makes the scsi-block device not removable by using HMP and QMP eject * command. */ s->features |= (1 << SCSI_DISK_F_NO_REMOVABLE_DEVOPS); return scsi_initfn(&s->qdev); }


configure_zone_ssutable(const cfg_obj_t *zconfig, dns_zone_t *zone,
			const char *zname)
{
	const cfg_obj_t *updatepolicy = NULL;
	const cfg_listelt_t *element, *element2;
	dns_ssutable_t *table = NULL;
	isc_mem_t *mctx = dns_zone_getmctx(zone);
	bool autoddns = false;
	isc_result_t result;

	(void)cfg_map_get(zconfig, "update-policy", &updatepolicy);

	if (updatepolicy == NULL) {
		dns_zone_setssutable(zone, NULL);
		return (ISC_R_SUCCESS);
	}

	if (cfg_obj_isstring(updatepolicy) &&
	    strcmp("local", cfg_obj_asstring(updatepolicy)) == 0) {
		autoddns = true;
		updatepolicy = NULL;
	}

	result = dns_ssutable_create(mctx, &table);
	if (result != ISC_R_SUCCESS)
		return (result);

	for (element = cfg_list_first(updatepolicy);
	     element != NULL;
	     element = cfg_list_next(element))
	{
		const cfg_obj_t *stmt = cfg_listelt_value(element);
		const cfg_obj_t *mode = cfg_tuple_get(stmt, "mode");
		const cfg_obj_t *identity = cfg_tuple_get(stmt, "identity");
		const cfg_obj_t *matchtype = cfg_tuple_get(stmt, "matchtype");
		const cfg_obj_t *dname = cfg_tuple_get(stmt, "name");
		const cfg_obj_t *typelist = cfg_tuple_get(stmt, "types");
		const char *str;
		bool grant = false;
		bool usezone = false;
		dns_ssumatchtype_t mtype = DNS_SSUMATCHTYPE_NAME;
		dns_fixedname_t fname, fident;
		isc_buffer_t b;
		dns_rdatatype_t *types;
		unsigned int i, n;

		str = cfg_obj_asstring(mode);
		if (strcasecmp(str, "grant") == 0) {
			grant = true;
		} else if (strcasecmp(str, "deny") == 0) {
			grant = false;
		} else {
			INSIST(0);
			ISC_UNREACHABLE();
		}

		str = cfg_obj_asstring(matchtype);
		CHECK(dns_ssu_mtypefromstring(str, &mtype));
		if (mtype == dns_ssumatchtype_subdomain) {
			usezone = true;
		}

		dns_fixedname_init(&fident);
		str = cfg_obj_asstring(identity);
		isc_buffer_constinit(&b, str, strlen(str));
		isc_buffer_add(&b, strlen(str));
		result = dns_name_fromtext(dns_fixedname_name(&fident), &b,
					   dns_rootname, 0, NULL);
		if (result != ISC_R_SUCCESS) {
			cfg_obj_log(identity, ns_g_lctx, ISC_LOG_ERROR,
				    "'%s' is not a valid name", str);
			goto cleanup;
		}

		dns_fixedname_init(&fname);
		if (usezone) {
			result = dns_name_copy(dns_zone_getorigin(zone),
					       dns_fixedname_name(&fname),
					       NULL);
			if (result != ISC_R_SUCCESS) {
				cfg_obj_log(identity, ns_g_lctx, ISC_LOG_ERROR,
					    "error copying origin: %s",
					    isc_result_totext(result));
				goto cleanup;
			}
		} else {
			str = cfg_obj_asstring(dname);
			isc_buffer_constinit(&b, str, strlen(str));
			isc_buffer_add(&b, strlen(str));
			result = dns_name_fromtext(dns_fixedname_name(&fname),
						   &b, dns_rootname, 0, NULL);
			if (result != ISC_R_SUCCESS) {
				cfg_obj_log(identity, ns_g_lctx, ISC_LOG_ERROR,
					    "'%s' is not a valid name", str);
				goto cleanup;
			}
		}

		n = ns_config_listcount(typelist);
		if (n == 0)
			types = NULL;
		else {
			types = isc_mem_get(mctx, n * sizeof(dns_rdatatype_t));
			if (types == NULL) {
				result = ISC_R_NOMEMORY;
				goto cleanup;
			}
		}

		i = 0;
		for (element2 = cfg_list_first(typelist);
		     element2 != NULL;
		     element2 = cfg_list_next(element2))
		{
			const cfg_obj_t *typeobj;
			isc_textregion_t r;

			INSIST(i < n);

			typeobj = cfg_listelt_value(element2);
			str = cfg_obj_asstring(typeobj);
			DE_CONST(str, r.base);
			r.length = strlen(str);

			result = dns_rdatatype_fromtext(&types[i++], &r);
			if (result != ISC_R_SUCCESS) {
				cfg_obj_log(identity, ns_g_lctx, ISC_LOG_ERROR,
					    "'%s' is not a valid type", str);
				isc_mem_put(mctx, types,
					    n * sizeof(dns_rdatatype_t));
				goto cleanup;
			}
		}
		INSIST(i == n);

		result = dns_ssutable_addrule(table, grant,
					      dns_fixedname_name(&fident),
					      mtype,
					      dns_fixedname_name(&fname),
					      n, types);
		if (types != NULL)
			isc_mem_put(mctx, types, n * sizeof(dns_rdatatype_t));
		if (result != ISC_R_SUCCESS) {
			goto cleanup;
		}
	}

	/*
	 * If "update-policy local;" and a session key exists,
	 * then use the default policy, which is equivalent to:
	 * update-policy { grant <session-keyname> zonesub any; };
	 */
	if (autoddns) {
		dns_rdatatype_t any = dns_rdatatype_any;

		if (ns_g_server->session_keyname == NULL) {
			isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
				      NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
				      "failed to enable auto DDNS policy "
				      "for zone %s: session key not found",
				      zname);
			result = ISC_R_NOTFOUND;
			goto cleanup;
		}

		result = dns_ssutable_addrule(table, true,
					      ns_g_server->session_keyname,
					      DNS_SSUMATCHTYPE_LOCAL,
					      dns_zone_getorigin(zone),
					      1, &any);

		if (result != ISC_R_SUCCESS)
			goto cleanup;
	}

	result = ISC_R_SUCCESS;
	dns_zone_setssutable(zone, table);

 cleanup:
	dns_ssutable_detach(&table);
	return (result);
}


static BLOCK_SIZE get_nonrd_var_based_fixed_partition ( VP9_COMP * cpi , int mi_row , int mi_col ) {
 unsigned int var = get_sby_perpixel_diff_variance ( cpi , & cpi -> mb . plane [ 0 ] . src , mi_row , mi_col , BLOCK_64X64 ) ;
 if ( var < 4 ) return BLOCK_64X64 ;
 else if ( var < 10 ) return BLOCK_32X32 ;
 else return BLOCK_16X16 ;
 }


tiff12_print_page(gx_device_printer * pdev, gp_file * file)
{
    gx_device_tiff *const tfdev = (gx_device_tiff *)pdev;
    int code;

    /* open the TIFF device */
    if (gdev_prn_file_is_new(pdev)) {
        tfdev->tif = tiff_from_filep(pdev, pdev->dname, file, tfdev->BigEndian, tfdev->UseBigTIFF);
        if (!tfdev->tif)
            return_error(gs_error_invalidfileaccess);
    }

    code = gdev_tiff_begin_page(tfdev, file);
    if (code < 0)
        return code;

    TIFFSetField(tfdev->tif, TIFFTAG_BITSPERSAMPLE, 4);
    tiff_set_rgb_fields(tfdev);

    TIFFCheckpointDirectory(tfdev->tif);

    /* Write the page data. */
    {
        int y;
        int size = gdev_prn_raster(pdev);
        byte *data = gs_alloc_bytes(pdev->memory, size, "tiff12_print_page");

        if (data == 0)
            return_error(gs_error_VMerror);

        memset(data, 0, size);

        for (y = 0; y < pdev->height; ++y) {
            const byte *src;
            byte *dest;
            int x;

            code = gdev_prn_copy_scan_lines(pdev, y, data, size);
            if (code < 0)
                break;

            for (src = data, dest = data, x = 0; x < size;
                 src += 6, dest += 3, x += 6
                ) {
                dest[0] = (src[0] & 0xf0) | (src[1] >> 4);
                dest[1] = (src[2] & 0xf0) | (src[3] >> 4);
                dest[2] = (src[4] & 0xf0) | (src[5] >> 4);
            }
            TIFFWriteScanline(tfdev->tif, data, y, 0);
        }
        gs_free_object(pdev->memory, data, "tiff12_print_page");

        TIFFWriteDirectory(tfdev->tif);
    }

    return code;
}