コード例 #1
0
void
il_quantize_fs_dither(il_container *ic, const uint8 *mask,
                      const uint8 *input_buf, int x_offset,
                      uint8 XP_HUGE *output_buf, int width)
{
    my_cquantize_ptr cquantize;
    register LOCFSERROR r_cur, g_cur, b_cur;       /* current error or pixel
                                                      value */
    LOCFSERROR r_belowerr, g_belowerr, b_belowerr; /* error for pixel below
                                                      cur */
    LOCFSERROR r_bpreverr, g_bpreverr, b_bpreverr; /* error for below/prev
                                                      col */
    LOCFSERROR r_bnexterr, g_bnexterr, b_bnexterr; /* error for below/next
                                                      col */
    LOCFSERROR delta;
    FSERRPTR r_errorptr, g_errorptr, b_errorptr;   /* fserrors[] at column
                                                      before current */
    const JSAMPLE* input_ptr;
    JSAMPLE XP_HUGE * output_ptr;
    IL_ColorMap *cmap = &ic->image->header.color_space->cmap;
    IL_RGB *map = cmap->map;              /* The colormap array. */
    IL_RGB *map_entry;                    /* Current entry in the colormap. */
    uint8 *lookup_table = cmap->table;    /* Lookup table for the colormap. */
    const uint8 *maskp;
    uint8 map_index;
    int dir;                   /* 1 for left-to-right, -1 for right-to-left */
    JDIMENSION col;
    JSAMPLE *range_limit = the_sample_range_limit;
    SHIFT_TEMPS

    cquantize = (my_cquantize_ptr) ic->quantize;
    
    output_buf += x_offset;

    /* Initialize output values to 0 so can process components separately */
    if (mask) {
        output_ptr = output_buf;
        maskp = mask;
        for (col = width; col > 0; col--)
            *output_ptr++ &= ~*maskp++;
    } else {
        XP_BZERO((void XP_HUGE *) output_buf,
                 (size_t) (width * SIZEOF(JSAMPLE)));
    }

    input_ptr = input_buf;
    output_ptr = output_buf;
    maskp = mask;
    if (cquantize->on_odd_row) {
        int total_offset;

        /* work right to left in this row */
        input_ptr += 3 * width - 1; /* so point to the blue sample of the
                                       rightmost pixel */
        output_ptr += width-1;
        dir = -1;
        /* => entry after last column */
        total_offset = x_offset + (width + 1);
        r_errorptr = cquantize->fserrors[0] + total_offset;
        g_errorptr = cquantize->fserrors[1] + total_offset;
        b_errorptr = cquantize->fserrors[2] + total_offset;
        maskp += (width - 1);
    } 
    else {
        /* work left to right in this row */
        dir = 1;
        /* => entry before first column */
        r_errorptr = cquantize->fserrors[0] + x_offset;
        g_errorptr = cquantize->fserrors[1] + x_offset;
        b_errorptr = cquantize->fserrors[2] + x_offset;
    }

    /* Preset error values: no error propagated to first pixel from left */
    r_cur = g_cur = b_cur = 0;

    /* and no error propagated to row below yet */
    r_belowerr = g_belowerr = b_belowerr = 0;
    r_bpreverr = g_bpreverr = b_bpreverr = 0;

    for (col = width; col > 0; col--) {
        /* cur holds the error propagated from the previous pixel on the
         * current line.  Add the error propagated from the previous line
         * to form the complete error correction term for this pixel, and
         * round the error term (which is expressed * 16) to an integer.
         * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
         * for either sign of the error value.
         * Note: errorptr points to *previous* column's array entry.
         */
        r_cur = RIGHT_SHIFT(r_cur + r_errorptr[dir] + 8, 4);
        g_cur = RIGHT_SHIFT(g_cur + g_errorptr[dir] + 8, 4);
        b_cur = RIGHT_SHIFT(b_cur + b_errorptr[dir] + 8, 4);

        /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
         * The maximum error is +- MAXJSAMPLE; this sets the required size
         * of the range_limit array.
         */
        if (dir > 0) {
            r_cur += GETJSAMPLE(*input_ptr);
            r_cur = GETJSAMPLE(range_limit[r_cur]);
            input_ptr++;
            g_cur += GETJSAMPLE(*input_ptr);
            g_cur = GETJSAMPLE(range_limit[g_cur]);
            input_ptr++;
            b_cur += GETJSAMPLE(*input_ptr);
            b_cur = GETJSAMPLE(range_limit[b_cur]);
            input_ptr++;
        }
        else {
            b_cur += GETJSAMPLE(*input_ptr);
            b_cur = GETJSAMPLE(range_limit[b_cur]);
            input_ptr--;
            g_cur += GETJSAMPLE(*input_ptr);
            g_cur = GETJSAMPLE(range_limit[g_cur]);
            input_ptr--;
            r_cur += GETJSAMPLE(*input_ptr);
            r_cur = GETJSAMPLE(range_limit[r_cur]);
            input_ptr--;
        }

        /* Select output value, accumulate into output code for this pixel */
        map_index = COLORMAP_INDEX(lookup_table, r_cur, g_cur, b_cur);
        if (mask) {
            if (*maskp)
                *output_ptr = map_index;
            maskp += dir;
        } else {
            *output_ptr = map_index;
        }

        /* Compute the actual representation error at this pixel */
        map_entry = map + map_index;
        r_cur -= GETJSAMPLE(map_entry->red);
        g_cur -= GETJSAMPLE(map_entry->green);
        b_cur -= GETJSAMPLE(map_entry->blue);

        /* Compute error fractions to be propagated to adjacent pixels.
         * Add these into the running sums, and simultaneously shift the
         * next-line error sums left by 1 column.
         */
        r_bnexterr = r_cur;
        delta = r_cur * 2;
        r_cur += delta;		/* form error * 3 */
        r_errorptr[0] = (FSERROR) (r_bpreverr + r_cur);
        r_cur += delta;		/* form error * 5 */
        r_bpreverr = r_belowerr + r_cur;
        r_belowerr = r_bnexterr;
        r_cur += delta;		/* form error * 7 */

        g_bnexterr = g_cur;
        delta = g_cur * 2;
        g_cur += delta;		/* form error * 3 */
        g_errorptr[0] = (FSERROR) (g_bpreverr + g_cur);
        g_cur += delta;		/* form error * 5 */
        g_bpreverr = g_belowerr + g_cur;
        g_belowerr = g_bnexterr;
        g_cur += delta;		/* form error * 7 */

        b_bnexterr = b_cur;
        delta = b_cur * 2;
        b_cur += delta;		/* form error * 3 */
        b_errorptr[0] = (FSERROR) (b_bpreverr + b_cur);
        b_cur += delta;		/* form error * 5 */
        b_bpreverr = b_belowerr + b_cur;
        b_belowerr = b_bnexterr;
        b_cur += delta;		/* form error * 7 */

        /* At this point cur contains the 7/16 error value to be propagated
         * to the next pixel on the current line, and all the errors for the
         * next line have been shifted over. We are therefore ready to move on.
         * Note: the input_ptr has already been advanced.
         */
        output_ptr += dir;	/* advance output ptr to next column */
        r_errorptr += dir;	/* advance errorptr to current column */
        g_errorptr += dir;	/* advance errorptr to current column */
        b_errorptr += dir;	/* advance errorptr to current column */
    }
    
    /* Post-loop cleanup: we must unload the final error value into the
     * final fserrors[] entry.  Note we need not unload belowerr because
     * it is for the dummy column before or after the actual array.
     */
    r_errorptr[0] = (FSERROR) r_bpreverr; /* unload prev err into array */
    g_errorptr[0] = (FSERROR) g_bpreverr; /* unload prev err into array */
    b_errorptr[0] = (FSERROR) b_bpreverr; /* unload prev err into array */

    cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
}
コード例 #2
0
INT_PTR CALLBACK DlgProcOptsConnections(HWND hWndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
	CMraProto *ppro = (CMraProto*)GetWindowLongPtr(hWndDlg, GWLP_USERDATA);
	CMStringW szBuff;

	switch (msg) {
	case WM_INITDIALOG:
		TranslateDialogDefault(hWndDlg);
		SetWindowLongPtr(hWndDlg, GWLP_USERDATA, lParam);
		ppro = (CMraProto*)lParam;

		if (ppro->mraGetStringW(NULL, "Server", szBuff))
			SetDlgItemText(hWndDlg, IDC_SERVER, szBuff.c_str());
		else
			SetDlgItemTextA(hWndDlg, IDC_SERVER, MRA_DEFAULT_SERVER);

		SetDlgItemInt(hWndDlg, IDC_SERVERPORT, ppro->getWord("ServerPort", MRA_DEFAULT_SERVER_PORT), FALSE);
		// if set SSL proxy, setting will ignored

		//CheckDlgButton(hWndDlg, IDC_KEEPALIVE, getByte("keepalive", 0));
		CheckDlgButton(hWndDlg, IDC_AUTO_ADD_CONTACTS_TO_SERVER, ppro->getByte("AutoAddContactsToServer", MRA_DEFAULT_AUTO_ADD_CONTACTS_TO_SERVER));
		CheckDlgButton(hWndDlg, IDC_AUTO_AUTH_REQ_ON_LOGON, ppro->getByte("AutoAuthRequestOnLogon", MRA_DEFAULT_AUTO_AUTH_REQ_ON_LOGON));
		CheckDlgButton(hWndDlg, IDC_AUTO_AUTH_GRAND_IN_CLIST, ppro->getByte("AutoAuthGrandUsersInCList", MRA_DEFAULT_AUTO_AUTH_GRAND_IN_CLIST));
		CheckDlgButton(hWndDlg, IDC_AUTO_AUTH_GRAND_NEW_USERS, ppro->getByte("AutoAuthGrandNewUsers", MRA_DEFAULT_AUTO_AUTH_GRAND_NEW_USERS));

		CheckDlgButton(hWndDlg, IDC_SLOWSEND, ppro->getByte("SlowSend", MRA_DEFAULT_SLOW_SEND));
		CheckDlgButton(hWndDlg, IDC_INCREMENTAL_NEW_MAIL_NOTIFY, ppro->getByte("IncrementalNewMailNotify", MRA_DEFAULT_INC_NEW_MAIL_NOTIFY));
		CheckDlgButton(hWndDlg, IDC_TRAYICON_NEW_MAIL_NOTIFY, ppro->getByte("TrayIconNewMailNotify", MRA_DEFAULT_TRAYICON_NEW_MAIL_NOTIFY));
		CheckDlgButton(hWndDlg, IDC_TRAYICON_NEW_MAIL_NOTIFY_CLICK_TO_INBOX, ppro->getByte("TrayIconNewMailClkToInbox", MRA_DEFAULT_TRAYICON_NEW_MAIL_CLK_TO_INBOX));
		EnableWindow(GetDlgItem(hWndDlg, IDC_TRAYICON_NEW_MAIL_NOTIFY_CLICK_TO_INBOX), ppro->getByte("TrayIconNewMailNotify", MRA_DEFAULT_TRAYICON_NEW_MAIL_NOTIFY));

		CheckDlgButton(hWndDlg, IDC_RTF_RECEIVE_ENABLE, ppro->getByte("RTFReceiveEnable", MRA_DEFAULT_RTF_RECEIVE_ENABLE));

		CheckDlgButton(hWndDlg, IDC_RTF_SEND_ENABLE, ppro->getByte("RTFSendEnable", MRA_DEFAULT_RTF_SEND_ENABLE));
		EnableWindow(GetDlgItem(hWndDlg, IDC_RTF_SEND_SMART), ppro->getByte("RTFSendEnable", MRA_DEFAULT_RTF_SEND_ENABLE));
		EnableWindow(GetDlgItem(hWndDlg, IDC_BUTTON_FONT), ppro->getByte("RTFSendEnable", MRA_DEFAULT_RTF_SEND_ENABLE));
		EnableWindow(GetDlgItem(hWndDlg, IDC_RTF_BGCOLOUR), ppro->getByte("RTFSendEnable", MRA_DEFAULT_RTF_SEND_ENABLE));
		SendDlgItemMessage(hWndDlg, IDC_RTF_BGCOLOUR, CPM_SETCOLOUR, 0, ppro->getDword("RTFBackgroundColour", MRA_DEFAULT_RTF_BACKGROUND_COLOUR));
		return TRUE;

	case WM_COMMAND:
		switch (LOWORD(wParam)) {
		case IDC_BUTTON_DEFAULT:
			SetDlgItemTextA(hWndDlg, IDC_SERVER, MRA_DEFAULT_SERVER);
			SetDlgItemInt(hWndDlg, IDC_SERVERPORT, MRA_DEFAULT_SERVER_PORT, FALSE);
			break;
		case IDC_TRAYICON_NEW_MAIL_NOTIFY:
			EnableWindow(GetDlgItem(hWndDlg, IDC_TRAYICON_NEW_MAIL_NOTIFY_CLICK_TO_INBOX), IsDlgButtonChecked(hWndDlg, IDC_TRAYICON_NEW_MAIL_NOTIFY));
			break;
		case IDC_RTF_SEND_ENABLE:
			EnableWindow(GetDlgItem(hWndDlg, IDC_RTF_SEND_SMART), IsDlgButtonChecked(hWndDlg, IDC_RTF_SEND_ENABLE));
			EnableWindow(GetDlgItem(hWndDlg, IDC_BUTTON_FONT), IsDlgButtonChecked(hWndDlg, IDC_RTF_SEND_ENABLE));
			EnableWindow(GetDlgItem(hWndDlg, IDC_RTF_BGCOLOUR), IsDlgButtonChecked(hWndDlg, IDC_RTF_SEND_ENABLE));
			break;
		case IDC_BUTTON_FONT:
			{
				LOGFONT lf = {0};
				CHOOSEFONT cf = {0};

				cf.lStructSize = sizeof(cf);
				cf.lpLogFont = &lf;
				cf.rgbColors = ppro->getDword("RTFFontColour", MRA_DEFAULT_RTF_FONT_COLOUR);
				cf.Flags = (CF_SCREENFONTS|CF_EFFECTS|CF_FORCEFONTEXIST|CF_INITTOLOGFONTSTRUCT);
				if (ppro->mraGetContactSettingBlob(NULL, "RTFFont", &lf, sizeof(LOGFONT), NULL) == FALSE) {
					HDC hDC = GetDC(NULL);// kegl
					lf.lfCharSet = MRA_DEFAULT_RTF_FONT_CHARSET;
					lf.lfHeight = -MulDiv(MRA_DEFAULT_RTF_FONT_SIZE, GetDeviceCaps(hDC, LOGPIXELSY), 72);
					lstrcpyn(lf.lfFaceName, MRA_DEFAULT_RTF_FONT_NAME, LF_FACESIZE);
					ReleaseDC(NULL, hDC);
				}

				if (ChooseFont(&cf)) {
					ppro->mraWriteContactSettingBlob(NULL, "RTFFont", &lf, sizeof(LOGFONT));
					ppro->setDword("RTFFontColour", cf.rgbColors);
				}
			}
			break;
		}

		if ((LOWORD(wParam) == IDC_SERVER || LOWORD(wParam) == IDC_SERVERPORT) && (HIWORD(wParam) != EN_CHANGE || (HWND)lParam != GetFocus())) return FALSE;
		SendMessage(GetParent(hWndDlg), PSM_CHANGED, 0, 0);
		break;
	case WM_NOTIFY:
		switch (((LPNMHDR)lParam)->code) {
		case PSN_APPLY:
			TCHAR szBuff[MAX_PATH];
			GetDlgItemText(hWndDlg, IDC_SERVER, szBuff, SIZEOF(szBuff));
			ppro->mraSetStringW(NULL, "Server", szBuff);
			ppro->setWord("ServerPort", (WORD)GetDlgItemInt(hWndDlg, IDC_SERVERPORT, NULL, FALSE));
			ppro->setByte("AutoAddContactsToServer", IsDlgButtonChecked(hWndDlg, IDC_AUTO_ADD_CONTACTS_TO_SERVER));
			ppro->setByte("AutoAuthRequestOnLogon", IsDlgButtonChecked(hWndDlg, IDC_AUTO_AUTH_REQ_ON_LOGON));
			ppro->setByte("AutoAuthGrandUsersInCList", IsDlgButtonChecked(hWndDlg, IDC_AUTO_AUTH_GRAND_IN_CLIST));
			ppro->setByte("AutoAuthGrandNewUsers", IsDlgButtonChecked(hWndDlg, IDC_AUTO_AUTH_GRAND_NEW_USERS));

			ppro->setByte("SlowSend", IsDlgButtonChecked(hWndDlg, IDC_SLOWSEND));
			ppro->setByte("IncrementalNewMailNotify", IsDlgButtonChecked(hWndDlg, IDC_INCREMENTAL_NEW_MAIL_NOTIFY));
			ppro->setByte("TrayIconNewMailNotify", IsDlgButtonChecked(hWndDlg, IDC_TRAYICON_NEW_MAIL_NOTIFY));
			ppro->setByte("TrayIconNewMailClkToInbox", IsDlgButtonChecked(hWndDlg, IDC_TRAYICON_NEW_MAIL_NOTIFY_CLICK_TO_INBOX));

			ppro->setByte("RTFReceiveEnable", IsDlgButtonChecked(hWndDlg, IDC_RTF_RECEIVE_ENABLE));
			ppro->setByte("RTFSendEnable", IsDlgButtonChecked(hWndDlg, IDC_RTF_SEND_ENABLE));
			ppro->setDword("RTFBackgroundColour", SendDlgItemMessage(hWndDlg, IDC_RTF_BGCOLOUR, CPM_GETCOLOUR, 0, 0));
			return TRUE;
		}
		break;
	}
	return FALSE;
}
コード例 #3
0
start_pass_fdctmgr (j_compress_ptr cinfo)
{
  j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
  fdct_ptr fdct = (fdct_ptr) lossyc->fdct_private;
  int ci, qtblno, i;
  jpeg_component_info *compptr;
  JQUANT_TBL * qtbl;
  DCTELEM * dtbl;

  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
       ci++, compptr++) {
    qtblno = compptr->quant_tbl_no;
    /* Make sure specified quantization table is present */
    if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
	cinfo->quant_tbl_ptrs[qtblno] == NULL)
      ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
    qtbl = cinfo->quant_tbl_ptrs[qtblno];
    /* Compute divisors for this quant table */
    /* We may do this more than once for same table, but it's not a big deal */
    switch (cinfo->dct_method) {
#ifdef DCT_ISLOW_SUPPORTED
    case JDCT_ISLOW:
      /* For LL&M IDCT method, divisors are equal to raw quantization
       * coefficients multiplied by 8 (to counteract scaling).
       */
      if (fdct->divisors[qtblno] == NULL) {
	fdct->divisors[qtblno] = (DCTELEM *)
	  (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
				      DCTSIZE2 * SIZEOF(DCTELEM));
      }
      dtbl = fdct->divisors[qtblno];
      for (i = 0; i < DCTSIZE2; i++) {
	dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
      }
      break;
#endif
#ifdef DCT_IFAST_SUPPORTED
    case JDCT_IFAST:
      {
	/* For AA&N IDCT method, divisors are equal to quantization
	 * coefficients scaled by scalefactor[row]*scalefactor[col], where
	 *   scalefactor[0] = 1
	 *   scalefactor[k] = cos(k*PI/16) * sqrt(2)    for k=1..7
	 * We apply a further scale factor of 8.
	 */
#define CONST_BITS 14
	static const INT16 aanscales[DCTSIZE2] = {
	  /* precomputed values scaled up by 14 bits */
	  16384, 22725, 21407, 19266, 16384, 12873,  8867,  4520,
	  22725, 31521, 29692, 26722, 22725, 17855, 12299,  6270,
	  21407, 29692, 27969, 25172, 21407, 16819, 11585,  5906,
	  19266, 26722, 25172, 22654, 19266, 15137, 10426,  5315,
	  16384, 22725, 21407, 19266, 16384, 12873,  8867,  4520,
	  12873, 17855, 16819, 15137, 12873, 10114,  6967,  3552,
	   8867, 12299, 11585, 10426,  8867,  6967,  4799,  2446,
	   4520,  6270,  5906,  5315,  4520,  3552,  2446,  1247
	};
	SHIFT_TEMPS

	if (fdct->divisors[qtblno] == NULL) {
	  fdct->divisors[qtblno] = (DCTELEM *)
	    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
					DCTSIZE2 * SIZEOF(DCTELEM));
	}
	dtbl = fdct->divisors[qtblno];
	for (i = 0; i < DCTSIZE2; i++) {
	  dtbl[i] = (DCTELEM)
	    DESCALE(MULTIPLY16V16((IJG_INT32) qtbl->quantval[i],
				  (IJG_INT32) aanscales[i]),
		    CONST_BITS-3);
	}
      }
      break;
#endif
#ifdef DCT_FLOAT_SUPPORTED
    case JDCT_FLOAT:
      {
	/* For float AA&N IDCT method, divisors are equal to quantization
	 * coefficients scaled by scalefactor[row]*scalefactor[col], where
	 *   scalefactor[0] = 1
	 *   scalefactor[k] = cos(k*PI/16) * sqrt(2)    for k=1..7
	 * We apply a further scale factor of 8.
	 * What's actually stored is 1/divisor so that the inner loop can
	 * use a multiplication rather than a division.
	 */
	FAST_FLOAT * fdtbl;
	int row, col;
	static const double aanscalefactor[DCTSIZE] = {
	  1.0, 1.387039845, 1.306562965, 1.175875602,
	  1.0, 0.785694958, 0.541196100, 0.275899379
	};

	if (fdct->float_divisors[qtblno] == NULL) {
	  fdct->float_divisors[qtblno] = (FAST_FLOAT *)
	    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
					DCTSIZE2 * SIZEOF(FAST_FLOAT));
	}
	fdtbl = fdct->float_divisors[qtblno];
	i = 0;
	for (row = 0; row < DCTSIZE; row++) {
	  for (col = 0; col < DCTSIZE; col++) {
	    fdtbl[i] = (FAST_FLOAT)
	      (1.0 / (((double) qtbl->quantval[i] *
		       aanscalefactor[row] * aanscalefactor[col] * 8.0)));
	    i++;
	  }
	}
      }
      break;
#endif
    default:
      ERREXIT(cinfo, JERR_NOT_COMPILED);
      break;
    }
  }
}
コード例 #4
0
ファイル: jdcolor.cpp プロジェクト: berndhs/satview
jinit_color_deconverter (j_decompress_ptr cinfo)
{
  my_cconvert_ptr cconvert;
  int ci;

  cconvert = (my_cconvert_ptr)
    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
				SIZEOF(my_color_deconverter));
  cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  cconvert->pub.start_pass = start_pass_dcolor;

  /* Make sure num_components agrees with jpeg_color_space */
  switch (cinfo->jpeg_color_space) {
  case JCS_GRAYSCALE:
    if (cinfo->num_components != 1)
      ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
    break;

  case JCS_RGB:
  case JCS_YCbCr:
    if (cinfo->num_components != 3)
      ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
    break;

  case JCS_CMYK:
  case JCS_YCCK:
    if (cinfo->num_components != 4)
      ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
    break;

  default:			/* JCS_UNKNOWN can be anything */
    if (cinfo->num_components < 1)
      ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
    break;
  }

  /* Set out_color_components and conversion method based on requested space.
   * Also clear the component_needed flags for any unused components,
   * so that earlier pipeline stages can avoid useless computation.
   */

  switch (cinfo->out_color_space) {
  case JCS_GRAYSCALE:
    cinfo->out_color_components = 1;
    if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
	cinfo->jpeg_color_space == JCS_YCbCr) {
      cconvert->pub.color_convert = grayscale_convert;
      /* For color->grayscale conversion, only the Y (0) component is needed */
      for (ci = 1; ci < cinfo->num_components; ci++)
	cinfo->comp_info[ci].component_needed = FALSE;
    } else
      ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
    break;

  case JCS_RGB:
    cinfo->out_color_components = RGB_PIXELSIZE;
    if (cinfo->jpeg_color_space == JCS_YCbCr) {
      cconvert->pub.color_convert = ycc_rgb_convert;
      build_ycc_rgb_table(cinfo);
    } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
      cconvert->pub.color_convert = gray_rgb_convert;
    } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
      cconvert->pub.color_convert = null_convert;
    } else
      ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
    break;

  case JCS_CMYK:
    cinfo->out_color_components = 4;
    if (cinfo->jpeg_color_space == JCS_YCCK) {
      cconvert->pub.color_convert = ycck_cmyk_convert;
      build_ycc_rgb_table(cinfo);
    } else if (cinfo->jpeg_color_space == JCS_CMYK) {
      cconvert->pub.color_convert = null_convert;
    } else
      ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
    break;

  default:
    /* Permit null conversion to same output space */
    if (cinfo->out_color_space == cinfo->jpeg_color_space) {
      cinfo->out_color_components = cinfo->num_components;
      cconvert->pub.color_convert = null_convert;
    } else			/* unsupported non-null conversion */
      ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
    break;
  }

  if (cinfo->quantize_colors)
    cinfo->output_components = 1; /* single colormapped output component */
  else
    cinfo->output_components = cinfo->out_color_components;
}
コード例 #5
0
ファイル: jccoefct.c プロジェクト: jrsnail/u2project_deps
compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
{
  my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  JDIMENSION MCU_col_num;	/* index of current MCU within row */
  JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  int blkn, bi, ci, yindex, yoffset, blockcnt;
  JDIMENSION ypos, xpos;
  jpeg_component_info *compptr;
  forward_DCT_ptr forward_DCT;

  /* Loop to write as much as one whole iMCU row */
  for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
       yoffset++) {
    for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
	 MCU_col_num++) {
      /* Determine where data comes from in input_buf and do the DCT thing.
       * Each call on forward_DCT processes a horizontal row of DCT blocks
       * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
       * sequentially.  Dummy blocks at the right or bottom edge are filled in
       * specially.  The data in them does not matter for image reconstruction,
       * so we fill them with values that will encode to the smallest amount of
       * data, viz: all zeroes in the AC entries, DC entries equal to previous
       * block's DC value.  (Thanks to Thomas Kinsman for this idea.)
       */
      blkn = 0;
      for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
	compptr = cinfo->cur_comp_info[ci];
	forward_DCT = cinfo->fdct->forward_DCT[compptr->component_index];
	blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
						: compptr->last_col_width;
	xpos = MCU_col_num * compptr->MCU_sample_width;
	ypos = yoffset * compptr->DCT_v_scaled_size;
	/* ypos == (yoffset+yindex) * DCTSIZE */
	for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
	  if (coef->iMCU_row_num < last_iMCU_row ||
	      yoffset+yindex < compptr->last_row_height) {
	    (*forward_DCT) (cinfo, compptr,
			    input_buf[compptr->component_index],
			    coef->MCU_buffer[blkn],
			    ypos, xpos, (JDIMENSION) blockcnt);
	    if (blockcnt < compptr->MCU_width) {
	      /* Create some dummy blocks at the right edge of the image. */
	      FMEMZERO((void FAR *) coef->MCU_buffer[blkn + blockcnt],
		       (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
	      for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
		coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
	      }
	    }
	  } else {
	    /* Create a row of dummy blocks at the bottom of the image. */
	    FMEMZERO((void FAR *) coef->MCU_buffer[blkn],
		     compptr->MCU_width * SIZEOF(JBLOCK));
	    for (bi = 0; bi < compptr->MCU_width; bi++) {
	      coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
	    }
	  }
	  blkn += compptr->MCU_width;
	  ypos += compptr->DCT_v_scaled_size;
	}
      }
      /* Try to write the MCU.  In event of a suspension failure, we will
       * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
       */
      if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
	/* Suspension forced; update state counters and exit */
	coef->MCU_vert_offset = yoffset;
	coef->mcu_ctr = MCU_col_num;
	return FALSE;
      }
    }
    /* Completed an MCU row, but perhaps not an iMCU row */
    coef->mcu_ctr = 0;
  }
  /* Completed the iMCU row, advance counters for next one */
  coef->iMCU_row_num++;
  start_iMCU_row(cinfo);
  return TRUE;
}
コード例 #6
0
ファイル: mu_rndwn_all.c プロジェクト: ChristyV/fis-gtm
/* Takes an entry from 'ipcs -m' and checks for its validity to be a GT.M db segment.
 * Returns TRUE if the shared memory segment is a valid GT.M db segment
 * (based on a check on some fields in the shared memory) else FALSE.
 * If the segment belongs to GT.M it returns the database file name by the second argument.
 * Sets exit_stat to ERR_MUNOTALLSEC if appropriate.
 */
boolean_t validate_db_shm_entry(shm_parms *parm_buff, char *fname, int *exit_stat)
{
	boolean_t		remove_shmid;
	file_control		*fc;
	int			fname_len, save_errno, status, shmid;
	node_local_ptr_t	nl_addr;
	sm_uc_ptr_t		start_addr;
	struct stat		st_buff;
	struct shmid_ds		shmstat;
	sgmnt_data		tsd;
	unix_db_info		*udi;
	char			msgbuff[OUT_BUFF_SIZE];

	if (NULL == parm_buff)
		return FALSE;
	/* check for the bare minimum size of the shared memory segment that we expect
	 * (with no fileheader related information at hand) */
	if (MIN_NODE_LOCAL_SPACE + SHMPOOL_SECTION_SIZE > parm_buff->sgmnt_siz)
		return FALSE;
	if (IPC_PRIVATE != parm_buff->key)
		return FALSE;
	shmid = parm_buff->shmid;
	/* we do not need to lock the shm for reading the rundown information as
	 * the other rundowns (if any) can also be allowed to share reading the
	 * same info concurrently.
	 */
	if (-1 == (sm_long_t)(start_addr = (sm_uc_ptr_t) do_shmat(shmid, 0, SHM_RND)))
		return FALSE;
	nl_addr = (node_local_ptr_t)start_addr;
	memcpy(fname, nl_addr->fname, MAX_FN_LEN + 1);
	fname[MAX_FN_LEN] = '\0';			/* make sure the fname is null terminated */
	fname_len = STRLEN(fname);
	msgbuff[0] = '\0';
	if (memcmp(nl_addr->label, GDS_LABEL, GDS_LABEL_SZ - 1))
	{
		if (!memcmp(nl_addr->label, GDS_LABEL, GDS_LABEL_SZ - 3))
		{
			util_out_print("Cannot rundown shmid = !UL for database !AD as it has format !AD "
				"but this mupip uses format !AD", TRUE, shmid,
				fname_len, fname, GDS_LABEL_SZ - 1, nl_addr->label, GDS_LABEL_SZ - 1, GDS_LABEL);
			*exit_stat = ERR_MUNOTALLSEC;
		}
		shmdt((void *)start_addr);
		return FALSE;
	}
	if (memcmp(nl_addr->now_running, gtm_release_name, gtm_release_name_len + 1))
	{
		SNPRINTF(msgbuff, OUT_BUFF_SIZE, "Cannot rundown database %s. Attempt to access with version %s, "
				"while already using %s", fname, gtm_release_name, nl_addr->now_running);
		PRINT_AND_SEND_DBRNDWN_FAILURE_MSG(msgbuff, fname, shmid);
		*exit_stat = ERR_MUNOTALLSEC;
		shmdt((void *)start_addr);
		return FALSE;
	}
	if (-1 == shmctl(shmid, IPC_STAT, &shmstat))
	{
		save_errno = errno;
		assert(FALSE);/* we were able to attach to this shmid before so should be able to get stats on it */
		util_out_print("!AD -> Error with shmctl for shmid = !UL",
			TRUE, fname_len, fname, shmid);
		gtm_putmsg(VARLSTCNT(1) save_errno);
		*exit_stat = ERR_MUNOTALLSEC;
		shmdt((void *)start_addr);
		return FALSE;
	}
	remove_shmid = FALSE;
	/* Check if db filename reported in shared memory still exists. If not, clean this shared memory section
	 * without even invoking "mu_rndwn_file" as that expects the db file to exist. Same case if shared memory
	 * points back to a database whose file header does not have this shmid.
	 */
	if (-1 == Stat(fname, &st_buff))
	{
		if (ENOENT == errno)
		{
			SNPRINTF(msgbuff, OUT_BUFF_SIZE, "File %s does not exist", fname);
			if (1 < shmstat.shm_nattch)
			{
				PRINT_AND_SEND_DBRNDWN_FAILURE_MSG(msgbuff, fname, shmid);
				*exit_stat = ERR_MUNOTALLSEC;
				shmdt((void *)start_addr);
				return FALSE;
			}
			remove_shmid = TRUE;
		} else
		{	/* Stat errored out e.g. due to file permissions. Log that */
			save_errno = errno;
			util_out_print("Cannot rundown shmid !UL for database file !AD as stat() on the file"
				" returned the following error", TRUE, shmid, fname_len, fname);
			gtm_putmsg(VARLSTCNT(1) save_errno);
			*exit_stat = ERR_MUNOTALLSEC;
			shmdt((void *)start_addr);
			return FALSE;
		}
	} else
	{
		mu_gv_cur_reg_init();
		gv_cur_region->dyn.addr->fname_len = strlen(fname);
		STRNCPY_STR(gv_cur_region->dyn.addr->fname, fname, gv_cur_region->dyn.addr->fname_len);
		fc = gv_cur_region->dyn.addr->file_cntl;
		fc->op = FC_OPEN;
		status = dbfilop(fc);
		if (SS_NORMAL != status)
		{
			util_out_print("!AD -> Error with dbfilop for shmid = !UL", TRUE, fname_len, fname, shmid);
			gtm_putmsg(VARLSTCNT(5) status, 2, DB_LEN_STR(gv_cur_region), errno);
			*exit_stat = ERR_MUNOTALLSEC;
			shmdt((void *)start_addr);
			return FALSE;
		}
		udi = FILE_INFO(gv_cur_region);
		LSEEKREAD(udi->fd, 0, &tsd, SIZEOF(sgmnt_data), status);
		if (0 != status)
		{
			save_errno = errno;
			util_out_print("!AD -> Error with LSEEKREAD for shmid = !UL", TRUE, fname_len, fname, shmid);
			gtm_putmsg(VARLSTCNT(1) save_errno);
			*exit_stat = ERR_MUNOTALLSEC;
			shmdt((void *)start_addr);
			return FALSE;
		}
		mu_gv_cur_reg_free();
		if (tsd.shmid != shmid)
		{
			SNPRINTF(msgbuff, OUT_BUFF_SIZE, "Shared memory ID (%d) in the DB file header does not match with the one"
					" reported by \"ipcs\" command (%d)", tsd.shmid, shmid);
			if (1 < shmstat.shm_nattch)
			{
				PRINT_AND_SEND_DBRNDWN_FAILURE_MSG(msgbuff, fname, shmid);
				*exit_stat = ERR_MUNOTALLSEC;
				shmdt((void *)start_addr);
				return FALSE;
			}
			remove_shmid = TRUE;
		} else if (tsd.gt_shm_ctime.ctime != shmstat.shm_ctime)
		{
			SNPRINTF(msgbuff, OUT_BUFF_SIZE, "Shared memory creation time in the DB file header does not match with"
					" the one reported by shmctl");
			if (1 < shmstat.shm_nattch)
			{
				PRINT_AND_SEND_DBRNDWN_FAILURE_MSG(msgbuff, fname, shmid);
				*exit_stat = ERR_MUNOTALLSEC;
				shmdt((void *)start_addr);
				return FALSE;
			}
			remove_shmid = TRUE;
		}
	}
	shmdt((void *)start_addr);
	if (remove_shmid)
	{
		assert('\0' != msgbuff[0]);
		if (0 != shm_rmid(shmid))
		{
			save_errno = errno;
			gtm_putmsg(VARLSTCNT(8) ERR_DBFILERR, 2, fname_len, fname,
				   ERR_TEXT, 2, RTS_ERROR_TEXT("Error removing shared memory"));
			util_out_print("!AD -> Error removing shared memory for shmid = !UL", TRUE, fname_len, fname, shmid);
			gtm_putmsg(VARLSTCNT(1) save_errno);
			*exit_stat = ERR_MUNOTALLSEC;
			return FALSE;
		}
		PRINT_AND_SEND_SHMREMOVED_MSG(msgbuff, fname_len, fname, shmid);
		*exit_stat = ERR_SHMREMOVED;
	} else
		*exit_stat = SS_NORMAL;
	return TRUE;
}
コード例 #7
0
ファイル: resolve_optimize.c プロジェクト: shabiel/YottaDB
boolean_t resolve_optimize(triple *curtrip)
{	/* a when all lines have been parsed optimization, current only applied for $TEXT() */
	int	i;
	mstr	*source_line;
	mval	tmp_mval, accumulator, *mval_x, *mval_y;
	triple	*ref, *y, *x, *triple_temp;
	triple	*line_offset, *label, *routine;
	src_line_struct	*cur_line;
	boolean_t negative, optimized = FALSE;
	/* If we are resolving indirect's or something of the sort, die sadly */
	assert(NULL != src_head.que.fl);
	switch (curtrip->opcode)
	{
	case OC_FNTEXT:
		/* If this is a OC_FNTEXT for the current routine, we can
			optimize it by simply inserting the text string from
			src_line_struct.que
		*/
		assert(OC_LITC != curtrip->operand[0].oprval.tref->opcode);
		routine = curtrip->operand[1].oprval.tref->operand[1].oprval.tref;
		line_offset = curtrip->operand[1].oprval.tref->operand[0].oprval.tref;
		label = curtrip->operand[0].oprval.tref;
		/* TODO: there should be a routine to verify literals for a given function */
		if (MLIT_REF != routine->operand[0].oprclass)
			break;
		if (!WANT_CURRENT_RTN(&routine->operand[0].oprval.mlit->v))
			break;
		if (MLIT_REF != label->operand[0].oprclass)
			break;
		if (ILIT_REF != line_offset->operand[0].oprclass)
			break;
		/* If we're here, we have a $TEXT with all literals for the current routine */
		source_line = (mstr *)mcalloc(SIZEOF(mstr));
		/* Special case; label == "" && +0 means file name */
		if (0 == label->operand[0].oprval.mlit->v.str.len
			&& 0 == line_offset->operand[0].oprval.ilit)
		{	/* Get filename, replace thing */
			/* Find last /; this is the start of the filename */
			source_line->len = routine_name.len;
			source_line->addr = malloc(source_line->len);
			memcpy(source_line->addr, routine_name.addr, source_line->len);
		} else
		{	/* Search through strings for label; if label == "" skip */
			cur_line = src_head.que.fl;
			negative = (0 > line_offset->operand[0].oprval.ilit);
			if (0 != label->operand[0].oprval.mlit->v.str.len && cur_line != cur_line->que.fl)
			{
				for (i = 0; cur_line != &src_head; cur_line = cur_line->que.fl)
				{
					if (label->operand[0].oprval.mlit->v.str.len > cur_line->str.len)
						continue;
					if (label->operand[0].oprval.mlit->v.str.len != cur_line->str.len)
					{
						switch (cur_line->str.addr[label->operand[0].oprval.mlit->v.str.len])
						{
							case ' ':
							case ';':
							case '(':
							case ':':
								break;
							default:
								/* If we get here, it means we have a superstring of the label;
								 * i.e. searching for "a" found "abc"
								 */
								continue;
						}
					}
					if (!strncmp(label->operand[0].oprval.mlit->v.str.addr, cur_line->str.addr,
						label->operand[0].oprval.mlit->v.str.len))
						break;
				}
				if (&src_head == cur_line)
					break;
					/* Error; let the runtime program deal with it for now */
			} else
			{	/* We need a special case to handle +0; if no label, it means start at top of file
					and we begin counting on 1,
					otherwise, it means the line that the label is on
				*/
				i = 1;
			}
			/* We could mod the offset by the size of the file, but hopefully no one is dumb enough to say +100000 */
			/* Counting the number of lines in the file will be O(n), not worth it */
			for (; i < (negative ? -1 : 1) * line_offset->operand[0].oprval.ilit && cur_line != &src_head; i++)
			{
				cur_line = (negative ? cur_line->que.bl : cur_line->que.fl);
			}
			/* If we went through all nodes and i is less than the line we are looking for, use an empty source line */
			if (&src_head == cur_line)
			{	/* Special case; we were counting backward, hit the end of the file, but we are done counting */
				/* This means we should output the name of the routine */
				if (i == (negative ? -1 : 1) * line_offset->operand[0].oprval.ilit
					&& negative)
				{
					source_line->len = routine_name.len;
					source_line->addr = malloc(source_line->len);
					memcpy(source_line->addr, routine_name.addr, source_line->len);
				} else
				{
					source_line->len = 0;
					source_line->addr = 0;
				}
			} else
			{
				source_line->len = cur_line->str.len;
				source_line->addr = malloc(source_line->len);
				memcpy(source_line->addr, cur_line->str.addr, cur_line->str.len);
			}
		}
		/* Insert literal into triple tree */
		tmp_mval.mvtype = MV_STR;
		/* Minus one so we don't copy newline character */
		tmp_mval.str.len = (source_line->len == 0 ? 0 :
			source_line->len - (source_line->addr[source_line->len-1] == '\n' ? 1 : 0));
		ENSURE_STP_FREE_SPACE(tmp_mval.str.len);
		tmp_mval.str.addr = (char *)stringpool.free;
		memcpy(tmp_mval.str.addr, source_line->addr, tmp_mval.str.len);
		/* Replace tab characters with spaces */
		for (i = 0; i < tmp_mval.str.len && tmp_mval.str.addr[i] != ';'; i++)
		{
			if ('\t' == tmp_mval.str.addr[i])
				tmp_mval.str.addr[i] = ' ';
		}
		stringpool.free += tmp_mval.str.len;
		if (source_line->addr != 0)
			free(source_line->addr);
		/* Update all things that referenced this value */
		curtrip->opcode = OC_LIT;
		put_lit_s(&tmp_mval, curtrip);
		label->opcode = OC_NOOP;
		line_offset = OC_NOOP;
		routine->opcode = OC_NOOP;
		optimized = TRUE;
		break;
		/* If no cases no optimizations to perform.... yet */
	}
	return optimized;
}
コード例 #8
0
ファイル: editlist.cpp プロジェクト: TonyAlloa/miranda-dev
void ChangeInfoData::EndListEdit(int save)
{
  if (hwndListEdit == NULL || iEditItem == -1 || this != dataListEdit) return;
  if (save) 
  {
    int iItem = SendMessage(hwndListEdit, LB_GETCURSEL, 0, 0);
    int i = SendMessage(hwndListEdit, LB_GETITEMDATA, iItem, 0);

    if (setting[iEditItem].dbType == DBVT_ASCIIZ) 
    {
      char *szNewValue = (((FieldNamesItem*)setting[iEditItem].pList)[i].text);
      if (((FieldNamesItem*)setting[iEditItem].pList)[i].code || setting[iEditItem].displayType & LIF_ZEROISVALID)
      { 
        settingData[iEditItem].changed = strcmpnull(szNewValue, (char*)settingData[iEditItem].value);
        SAFE_FREE((void**)&settingData[iEditItem].value);
        settingData[iEditItem].value = (LPARAM)null_strdup(szNewValue);
      }
      else 
      {
        settingData[iEditItem].changed = (char*)settingData[iEditItem].value!=NULL;
        SAFE_FREE((void**)&settingData[iEditItem].value);
      }
    }
    else 
    {
      settingData[iEditItem].changed = ((FieldNamesItem*)setting[iEditItem].pList)[i].code != settingData[iEditItem].value;
      settingData[iEditItem].value = ((FieldNamesItem*)setting[iEditItem].pList)[i].code;
    }
    if (settingData[iEditItem].changed)
    {
      char buf[MAX_PATH];
      TCHAR tbuf[MAX_PATH];

      if (utf8_to_tchar_static(ICQTranslateUtfStatic(((FieldNamesItem*)setting[iEditItem].pList)[i].text, buf, SIZEOF(buf)), tbuf, SIZEOF(buf)))
        ListView_SetItemText(hwndList, iEditItem, 1, tbuf);

      EnableDlgItem(GetParent(hwndList), IDC_SAVE, TRUE);

    }
  }
  ListView_RedrawItems(hwndList, iEditItem, iEditItem);
  iEditItem = -1;
  dataListEdit = NULL;
  DestroyWindow(hwndListEdit);
  hwndListEdit = NULL;
}
コード例 #9
0
ファイル: test-perror2.c プロジェクト: AGSaidi/hacked-libvirt
int
main (void)
{
  /* We change fd 2 later, so save it in fd 10.  */
  if (dup2 (STDERR_FILENO, BACKUP_STDERR_FILENO) != BACKUP_STDERR_FILENO
      || (myerr = fdopen (BACKUP_STDERR_FILENO, "w")) == NULL)
    return 2;

  ASSERT (freopen (BASE ".tmp", "w+", stderr) == stderr);

  /* Test that perror does not clobber strerror buffer.  */
  {
    const char *msg1;
    const char *msg2;
    const char *msg3;
    const char *msg4;
    char *str1;
    char *str2;
    char *str3;
    char *str4;

    msg1 = strerror (ENOENT);
    ASSERT (msg1);
    str1 = strdup (msg1);
    ASSERT (str1);

    msg2 = strerror (ERANGE);
    ASSERT (msg2);
    str2 = strdup (msg2);
    ASSERT (str2);

    msg3 = strerror (-4);
    ASSERT (msg3);
    str3 = strdup (msg3);
    ASSERT (str3);

    msg4 = strerror (1729576);
    ASSERT (msg4);
    str4 = strdup (msg4);
    ASSERT (str4);

    errno = EACCES;
    perror ("");
    errno = -5;
    perror ("");
    ASSERT (!ferror (stderr));
    ASSERT (msg1 == msg2 || msg1 == msg4 || STREQ (msg1, str1));
    ASSERT (msg2 == msg4 || STREQ (msg2, str2));
    ASSERT (msg3 == msg4 || STREQ (msg3, str3));
    ASSERT (STREQ (msg4, str4));

    free (str1);
    free (str2);
    free (str3);
    free (str4);
  }

  /* Test that perror uses the same message as strerror.  */
  {
    int errs[] = { EACCES, 0, -3, };
    int i;
    for (i = 0; i < SIZEOF (errs); i++)
      {
        char buf[256];
        char *err = strerror (errs[i]);

        ASSERT (err);
        ASSERT (strlen (err) < sizeof buf);
        rewind (stderr);
        ASSERT (ftruncate (fileno (stderr), 0) == 0);
        errno = errs[i];
        perror (NULL);
        ASSERT (!ferror (stderr));
        rewind (stderr);
        ASSERT (fgets (buf, sizeof buf, stderr) == buf);
        ASSERT (strstr (buf, err));
      }
  }

  /* Test that perror reports write failure.  */
  {
    ASSERT (freopen (BASE ".tmp", "r", stderr) == stderr);
    ASSERT (setvbuf (stderr, NULL, _IONBF, BUFSIZ) == 0);
    errno = -1;
    ASSERT (!ferror (stderr));
    perror (NULL);
#if 0
    /* Commented out until cygwin behaves:
       http://sourceware.org/ml/newlib/2011/msg00228.html */
    ASSERT (errno > 0);
    /* Commented out until glibc behaves:
       http://sourceware.org/bugzilla/show_bug.cgi?id=12792 */
    ASSERT (ferror (stderr));
#endif
  }

  ASSERT (fclose (stderr) == 0);
  ASSERT (remove (BASE ".tmp") == 0);

  return 0;
}
コード例 #10
0
ファイル: icons.cpp プロジェクト: HornyHorse79/mirotr
void DeinitIcons() {
	for ( int i = 0; i < SIZEOF(iconList); i++ ) {
		(HANDLE)CallService(MS_SKIN2_REMOVEICON, 0, (LPARAM)iconList[i].szName);
		hIconLibItem[i] = NULL;
	}
}
コード例 #11
0
ファイル: rdswitch.c プロジェクト: Rambonuaa/BoundCheck4
read_scan_script (j_compress_ptr cinfo, char * filename)
/* Read a scan script from the specified text file.
 * Each entry in the file defines one scan to be emitted.
 * Entries are separated by semicolons ';'.
 * An entry contains one to four component indexes,
 * optionally followed by a colon ':' and four progressive-JPEG parameters.
 * The component indexes denote which component(s) are to be transmitted
 * in the current scan.  The first component has index 0.
 * Sequential JPEG is used if the progressive-JPEG parameters are omitted.
 * The file is free format text: any whitespace may appear between numbers
 * and the ':' and ';' punctuation marks.  Also, other punctuation (such
 * as commas or dashes) can be placed between numbers if desired.
 * Comments preceded by '#' may be included in the file.
 * Note: we do very little validity checking here;
 * jcmaster.c will validate the script parameters.
 */
{
  FILE * fp;
__boundcheck_metadata_store((void *)(&fp),(void *)((size_t)(&fp)+sizeof(fp)*8-1));

  int scanno;
__boundcheck_metadata_store((void *)(&scanno),(void *)((size_t)(&scanno)+sizeof(scanno)*8-1));
int  ncomps;
__boundcheck_metadata_store((void *)(&ncomps),(void *)((size_t)(&ncomps)+sizeof(ncomps)*8-1));
int  termchar;
__boundcheck_metadata_store((void *)(&termchar),(void *)((size_t)(&termchar)+sizeof(termchar)*8-1));

  long val;
__boundcheck_metadata_store((void *)(&val),(void *)((size_t)(&val)+sizeof(val)*8-1));

  jpeg_scan_info * scanptr;
__boundcheck_metadata_store((void *)(&scanptr),(void *)((size_t)(&scanptr)+sizeof(scanptr)*8-1));

#define MAX_SCANS  100		/* quite arbitrary limit */
  jpeg_scan_info scans[MAX_SCANS];__boundcheck_metadata_store(&scans[0],&scans[100-1]);


  if ((fp = fopen(filename, "r")) == NULL) {
    fprintf(stderr, "Can't open scan definition file %s\n", filename);
    return FALSE;
  }
  scanptr = scans;
__boundcheck_metadata_trans_check((void *)(scanptr),(void *)(scans),(void *)(scans));

  scanno = 0;

  while (read_scan_integer(fp, &val, &termchar)) {
    if (scanno >= MAX_SCANS) {
      fprintf(stderr, "Too many scans defined in file %s\n", filename);
      fclose(fp);
      return FALSE;
    }
    scanptr->component_index[_RV_insert_check(0,4,195,5,"read_scan_script",0)] = (int) val;
    ncomps = 1;
    while (termchar == ' ') {
      if (ncomps >= MAX_COMPS_IN_SCAN) {
	fprintf(stderr, "Too many components in one scan in file %s\n",
		filename);
	fclose(fp);
	return FALSE;
      }
      if (! read_scan_integer(fp, &val, &termchar))
	goto bogus;
      scanptr->component_index[_RV_insert_check(0,4,206,7,"read_scan_script",ncomps)] = (int) val;
      ncomps++;
    }
    scanptr->comps_in_scan = ncomps;
    if (termchar == ':') {
      if (! read_scan_integer(fp, &val, &termchar) || termchar != ' ')
	goto bogus;
      scanptr->Ss = (int) val;
      if (! read_scan_integer(fp, &val, &termchar) || termchar != ' ')
	goto bogus;
      scanptr->Se = (int) val;
      if (! read_scan_integer(fp, &val, &termchar) || termchar != ' ')
	goto bogus;
      scanptr->Ah = (int) val;
      if (! read_scan_integer(fp, &val, &termchar))
	goto bogus;
      scanptr->Al = (int) val;
    } else {
      /* set non-progressive parameters */
      scanptr->Ss = 0;
      scanptr->Se = DCTSIZE2-1;
      scanptr->Ah = 0;
      scanptr->Al = 0;
    }
    if (termchar != ';' && termchar != EOF) {
bogus:
      fprintf(stderr, "Invalid scan entry format in file %s\n", filename);
      fclose(fp);
      return FALSE;
    }
    scanptr++, scanno++;
  }

  if (termchar != EOF) {
    fprintf(stderr, "Non-numeric data in file %s\n", filename);
    fclose(fp);
    return FALSE;
  }

  if (scanno > 0) {
    /* Stash completed scan list in cinfo structure.
     * NOTE: for cjpeg's use, JPOOL_IMAGE is the right lifetime for this data,
     * but if you want to compress multiple images you'd want JPOOL_PERMANENT.
     */
    scanptr = (jpeg_scan_info *)
      (*(void *(*)(j_common_ptr, int, size_t))(__boundcheck_ptr_reference(251,21,"read_scan_script",(void *)(cinfo->mem->alloc_small),(void *)cinfo->mem->alloc_small))) ((j_common_ptr) cinfo, JPOOL_IMAGE,
				  scanno * SIZEOF(jpeg_scan_info));
    MEMCOPY(scanptr, scans, scanno * SIZEOF(jpeg_scan_info));
    cinfo->scan_info = scanptr;
    cinfo->num_scans = scanno;
  }

  fclose(fp);
  return TRUE;
}
コード例 #12
0
ファイル: icons.cpp プロジェクト: HornyHorse79/mirotr
struct
{
	const TCHAR* stzDescr;
	const char* szName;
	int   defIconID;
}
static iconList[] = {
	{	_T(LANG_ICON_OTR),			ICON_OTR,			IDI_OTR			},
	{	_T(LANG_ICON_PRIVATE),		ICON_PRIVATE,		IDI_PRIVATE		},
	{	_T(LANG_ICON_UNVERIFIED),	ICON_UNVERIFIED,	IDI_UNVERIFIED	},
	{	_T(LANG_ICON_FINISHED),		ICON_FINISHED,		IDI_FINISHED	},
	{	_T(LANG_ICON_NOT_PRIVATE),	ICON_NOT_PRIVATE,	IDI_INSECURE	}
	
};

HANDLE hIconLibItem[SIZEOF(iconList)];

void InitIcons() {
	TCHAR szFile[MAX_PATH+500];

	GetModuleFileName(hInst, szFile, SIZEOF(szFile));

	SKINICONDESC sid = {0};
	sid.cbSize = sizeof(SKINICONDESC);
	sid.ptszDefaultFile = szFile;
	sid.ptszSection = _T(MODULENAME);
	sid.flags = SIDF_ALL_TCHAR;

	for ( int i = 0; i < SIZEOF(iconList); i++ ) {
		sid.pszName = (char*)iconList[i].szName;
		sid.ptszDescription = (TCHAR*)iconList[i].stzDescr;
コード例 #13
0
ファイル: receive.cpp プロジェクト: martok/miranda-ng
//This function handles the ACK received from that hooked.
int handleAckSMS(WPARAM wParam, LPARAM lParam)
{
	if ( !lParam)
		return 0;
	if (((ACKDATA*)lParam)->type != ICQACKTYPE_SMS)
		return 0;

	char szPhone[MAX_PHONE_LEN] = { 0 };
	TCHAR tszPhone[MAX_PHONE_LEN] = { 0 };
	LPSTR lpszXML = (LPSTR)((ACKDATA*)lParam)->lParam, lpszData, lpszPhone;
	size_t dwXMLSize = 0, dwDataSize, dwPhoneSize;
	ACKDATA *ack = ((ACKDATA*)lParam);

	if (lpszXML)
		dwXMLSize = mir_strlen(lpszXML);

	if (GetXMLFieldEx(lpszXML,dwXMLSize,&lpszData,&dwDataSize,"sms_message", "text", NULL))
	{
		if (GetXMLFieldEx(lpszXML,dwXMLSize,&lpszPhone,&dwPhoneSize,"sms_message","sender",NULL))
		{
			LPSTR lpszMessageUTF;
			size_t dwBuffLen,dwMessageXMLEncodedSize,dwMessageXMLDecodedSize;
			DBEVENTINFO dbei = { sizeof(dbei) };

			dwBuffLen=(dwDataSize+MAX_PATH);
			dbei.pBlob=(LPBYTE)MEMALLOC((dwBuffLen+dwPhoneSize));
			LPWSTR lpwszMessageXMLEncoded=(LPWSTR)MEMALLOC((dwBuffLen*sizeof(WCHAR)));
			LPWSTR lpwszMessageXMLDecoded=(LPWSTR)MEMALLOC((dwBuffLen*sizeof(WCHAR)));
			if (dbei.pBlob && lpwszMessageXMLEncoded && lpwszMessageXMLDecoded)
			{
				dwMessageXMLEncodedSize=MultiByteToWideChar(CP_UTF8,0,lpszData,dwDataSize,lpwszMessageXMLEncoded,dwBuffLen);
				DecodeXML(lpwszMessageXMLEncoded,dwMessageXMLEncodedSize,lpwszMessageXMLDecoded,dwBuffLen,&dwMessageXMLDecodedSize);
				lpszMessageUTF=(LPSTR)lpwszMessageXMLEncoded;
				WideCharToMultiByte(CP_UTF8,0,lpwszMessageXMLDecoded,dwMessageXMLDecodedSize,lpszMessageUTF,dwBuffLen,NULL,NULL);

				dwPhoneSize=CopyNumberA(szPhone,lpszPhone,dwPhoneSize);
				dwPhoneSize=MultiByteToWideChar(CP_UTF8,0,szPhone,dwPhoneSize,tszPhone,MAX_PHONE_LEN);
				MCONTACT hContact=HContactFromPhone(tszPhone,dwPhoneSize);

				dbei.szModule=GetModuleName(hContact);
				dbei.timestamp=time(NULL);
				dbei.flags = DBEF_UTF;
				dbei.eventType = ICQEVENTTYPE_SMS;
				dbei.cbBlob=(mir_snprintf((LPSTR)dbei.pBlob,((dwBuffLen+dwPhoneSize)),"SMS From: +%s\r\n%s",szPhone,lpszMessageUTF)+sizeof(DWORD));
				//dbei.pBlob=(LPBYTE)lpszBuff;
				(*((DWORD*)(dbei.pBlob+(dbei.cbBlob-sizeof(DWORD)))))=0;
				HANDLE hResult = db_event_add(hContact, &dbei);
				if (hContact==NULL) {	
					if ( RecvSMSWindowAdd(NULL,ICQEVENTTYPE_SMS,tszPhone,dwPhoneSize,(LPSTR)dbei.pBlob,dbei.cbBlob)) {
						db_event_markRead(hContact, hResult);
						SkinPlaySound("RecvSMSMsg");
					}
				}
			}
			MEMFREE(lpwszMessageXMLDecoded);
			MEMFREE(lpwszMessageXMLEncoded);
			MEMFREE(dbei.pBlob);
		}
	}else
	if (GetXMLFieldEx(lpszXML,dwXMLSize,&lpszData,&dwDataSize,"sms_delivery_receipt","delivered",NULL))
	{
		if (GetXMLFieldEx(lpszXML,dwXMLSize,&lpszPhone,&dwPhoneSize,"sms_delivery_receipt","destination",NULL))
		{
			dwPhoneSize=CopyNumberA(szPhone,lpszPhone,dwPhoneSize);
			dwPhoneSize=MultiByteToWideChar(CP_UTF8,0,szPhone,dwPhoneSize,tszPhone,MAX_PHONE_LEN);
			MCONTACT hContact=HContactFromPhone(tszPhone,dwPhoneSize);

			DBEVENTINFO dbei={0};
			dbei.cbSize=sizeof(dbei);
			dbei.szModule=GetModuleName(hContact);
			dbei.timestamp=time(NULL);
			dbei.flags = DBEF_UTF;
			dbei.eventType = ICQEVENTTYPE_SMSCONFIRMATION;
			if (CompareStringA(MAKELANGID(LANG_ENGLISH,SUBLANG_ENGLISH_US),NORM_IGNORECASE,lpszData,dwDataSize,"yes",3)==CSTR_EQUAL)
			{
				dbei.cbBlob=(MAX_PHONE_LEN+MAX_PATH);
				dbei.pBlob=(PBYTE)MEMALLOC(dbei.cbBlob);
				if (dbei.pBlob) dbei.cbBlob=(mir_snprintf((LPSTR)dbei.pBlob,dbei.cbBlob,"SMS Confirmation From: +%s\r\nSMS was sent succesfully",szPhone)+4);
			}else{
				if (GetXMLFieldEx(lpszXML,dwXMLSize,&lpszData,&dwDataSize,"sms_delivery_receipt","error","params","param",NULL)==FALSE)
				{
					lpszData="";
					dwDataSize=0;
				}
				dbei.cbBlob=(MAX_PHONE_LEN+MAX_PATH+dwDataSize);
				dbei.pBlob=(PBYTE)MEMALLOC(dbei.cbBlob);
				if (dbei.pBlob)
				{
					dbei.cbBlob=mir_snprintf((LPSTR)dbei.pBlob,dbei.cbBlob,"SMS Confirmation From: +%s\r\nSMS was not sent succesfully: ",szPhone);
					memcpy((dbei.pBlob+dbei.cbBlob),lpszData,dwDataSize);
					dbei.cbBlob+=(dwDataSize+sizeof(DWORD));
					(*((DWORD*)(dbei.pBlob+(dbei.cbBlob-sizeof(DWORD)))))=0;
				}
			}

			if (dbei.pBlob) {
				if (hContact)
					db_event_add(hContact, &dbei);
				else
					RecvSMSWindowAdd(NULL,ICQEVENTTYPE_SMSCONFIRMATION,tszPhone,dwPhoneSize,(LPSTR)dbei.pBlob,dbei.cbBlob);

				MEMFREE(dbei.pBlob);
			}
		}
	}else
	if ((ack->result == ACKRESULT_FAILED) || GetXMLFieldEx(lpszXML,dwXMLSize,&lpszData,&dwDataSize,"sms_response","deliverable",NULL))
	{
		HWND hWndDlg = SendSMSWindowHwndByHProcessGet(ack->hProcess);
		if (hWndDlg) {
			char szNetwork[MAX_PATH];

			KillTimer(hWndDlg, wParam);
			GetXMLFieldExBuff(lpszXML,dwXMLSize,szNetwork,sizeof(szNetwork),NULL,"sms_response","network",NULL);

			if (ack->result == ACKRESULT_FAILED || CompareStringA(MAKELANGID(LANG_ENGLISH,SUBLANG_ENGLISH_US),NORM_IGNORECASE,lpszData,dwDataSize,"no",2)==CSTR_EQUAL) {	
				char szBuff[1024];
				TCHAR tszErrorMessage[1028];
				LPSTR lpszErrorDescription;

				if (SendSMSWindowMultipleGet(hWndDlg)) {
					TVITEM tvi;
					tvi.mask=TVIF_TEXT;
					tvi.hItem=SendSMSWindowHItemSendGet(hWndDlg);
					tvi.pszText=tszPhone;
					tvi.cchTextMax=SIZEOF(tszPhone);
					TreeView_GetItem(GetDlgItem(hWndDlg,IDC_NUMBERSLIST),&tvi);
				}
				else GetDlgItemText(hWndDlg,IDC_ADDRESS,tszPhone,SIZEOF(szPhone));

				if (ack->result == ACKRESULT_FAILED)
					lpszErrorDescription=lpszXML;
				else {
					lpszErrorDescription=szBuff;
					GetXMLFieldExBuff(lpszXML,dwXMLSize,szBuff,sizeof(szBuff),NULL,"sms_response","error","params","param",NULL);
				}

				mir_sntprintf(tszErrorMessage,SIZEOF(tszErrorMessage),TranslateT("SMS message didn't send by %S to %s because: %S"),szNetwork,tszPhone,lpszErrorDescription);
				ShowWindow(hWndDlg,SW_SHOWNORMAL);
				EnableWindow(hWndDlg,FALSE);
				HWND hwndTimeOut=CreateDialog(ssSMSSettings.hInstance,MAKEINTRESOURCE(IDD_SENDSMSTIMEDOUT),hWndDlg,SMSTimedOutDlgProc);
				SetDlgItemText(hwndTimeOut,IDC_STATUS,tszErrorMessage);
			}
			else {
				SendSMSWindowDBAdd(hWndDlg);
				if ( SendSMSWindowMultipleGet(hWndDlg)) {
					if ( SendSMSWindowNextHItemGet(hWndDlg,SendSMSWindowHItemSendGet(hWndDlg))) {
						SendSMSWindowAsSentSet(hWndDlg);
						SendSMSWindowHItemSendSet(hWndDlg,SendSMSWindowNextHItemGet(hWndDlg,SendSMSWindowHItemSendGet(hWndDlg)));
						SendSMSWindowNext(hWndDlg);
					}
					else SendSMSWindowRemove(hWndDlg);
				}
				else {
					if ( CompareStringA(MAKELANGID(LANG_ENGLISH,SUBLANG_ENGLISH_US),NORM_IGNORECASE,lpszData,dwDataSize,"yes",3)==CSTR_EQUAL ||
							CompareStringA(MAKELANGID(LANG_ENGLISH,SUBLANG_ENGLISH_US),NORM_IGNORECASE,lpszData,dwDataSize,"smtp",4)==CSTR_EQUAL) {
						char szSource[MAX_PATH],szMessageID[MAX_PATH];

						if (DB_SMS_GetByte(NULL,"ShowACK",SMS_DEFAULT_SHOWACK)) {	
							HWND hwndAccepted=CreateDialog(ssSMSSettings.hInstance,MAKEINTRESOURCE(IDD_SENDSMSACCEPT),hWndDlg,SMSAcceptedDlgProc);
							if (CompareStringA(MAKELANGID(LANG_ENGLISH,SUBLANG_ENGLISH_US),NORM_IGNORECASE,lpszData,dwDataSize,"yes",3)==CSTR_EQUAL) {
								GetXMLFieldExBuff(lpszXML,dwXMLSize,szSource,sizeof(szSource),NULL,"sms_response","source",NULL);
								GetXMLFieldExBuff(lpszXML,dwXMLSize,szMessageID,sizeof(szMessageID),NULL,"sms_response","message_id",NULL);
							}
							else {
								SetDlgItemText(hwndAccepted,IDC_ST_SOURCE,TranslateT("From:"));
								SetDlgItemText(hwndAccepted,IDC_ST_MESSAGEID,TranslateT("To:"));
								GetXMLFieldExBuff(lpszXML,dwXMLSize,szSource,sizeof(szSource),NULL,"sms_response","from",NULL);
								GetXMLFieldExBuff(lpszXML,dwXMLSize,szMessageID,sizeof(szMessageID),NULL,"sms_response","to",NULL);
							}
							SetDlgItemTextA(hwndAccepted,IDC_NETWORK,szNetwork);
							SetDlgItemTextA(hwndAccepted,IDC_SOURCE,szSource);
							SetDlgItemTextA(hwndAccepted,IDC_MESSAGEID,szMessageID);
						}
						else SendSMSWindowRemove(hWndDlg);
					}
					else SendSMSWindowRemove(hWndDlg);
				}
			}
		}
	}
	return 0;
}
コード例 #14
0
ファイル: receive.cpp プロジェクト: martok/miranda-ng
//Handles new SMS messages added to the database
int handleNewMessage(WPARAM hContact, LPARAM lParam)
{
	char szServiceFunction[MAX_PATH], *pszServiceFunctionName;
	TCHAR szToolTip[MAX_PATH];
	HANDLE hDbEvent = (HANDLE)lParam;
	DBEVENTINFO dbei = { sizeof(dbei) };
	
	if ((dbei.cbBlob = db_event_getBlobSize(hDbEvent)) == -1)
		return 0;

	dbei.pBlob = (PBYTE)MEMALLOC(dbei.cbBlob);
	if ( !dbei.pBlob)
		return 0;
	memcpy(szServiceFunction,PROTOCOL_NAMEA,PROTOCOL_NAME_SIZE);
	pszServiceFunctionName = szServiceFunction + PROTOCOL_NAME_LEN;

	if (db_event_get(hDbEvent, &dbei) == 0)
	if ((dbei.flags & DBEF_SENT) == 0)
	if (dbei.eventType == ICQEVENTTYPE_SMS) {
		if (dbei.cbBlob>MIN_SMS_DBEVENT_LEN) {
			SkinPlaySound("RecvSMSMsg");
			if (DB_SMS_GetByte(NULL,"AutoPopup",0)) {
				if (RecvSMSWindowAdd(hContact,ICQEVENTTYPE_SMS,NULL,0,(LPSTR)dbei.pBlob,dbei.cbBlob))
					db_event_markRead(hContact, hDbEvent);
			}
			else {
				memcpy(pszServiceFunctionName,SMS_READ,sizeof(SMS_READ));
				mir_sntprintf(szToolTip,SIZEOF(szToolTip),TranslateT("SMS Message from %s"),GetContactNameW(hContact));

				CLISTEVENT cle = { sizeof(cle) };
				cle.flags = CLEF_TCHAR;
				cle.hContact = hContact;
				cle.hDbEvent = hDbEvent;
				cle.hIcon = LoadSkinnedIcon(SKINICON_OTHER_SMS);
				cle.pszService = szServiceFunction;
				cle.ptszTooltip = szToolTip;
				CallService(MS_CLIST_ADDEVENT,0,(LPARAM)&cle);
			}
		}
	}
	else if (dbei.eventType == ICQEVENTTYPE_SMSCONFIRMATION) {
		SkinPlaySound("RecvSMSConfirmation");
		if (DB_SMS_GetByte(NULL, "AutoPopup", 0)) {
			if (RecvSMSWindowAdd(hContact,ICQEVENTTYPE_SMSCONFIRMATION,NULL,0,(LPSTR)dbei.pBlob,dbei.cbBlob))
				db_event_delete(hContact, &dbei);
		}
		else {
			UINT iIcon;
			if (GetDataFromMessage((LPSTR)dbei.pBlob, dbei.cbBlob, NULL, NULL, 0, NULL, &iIcon)) {
				memcpy(pszServiceFunctionName,SMS_READ_ACK,sizeof(SMS_READ_ACK));
				mir_sntprintf(szToolTip,SIZEOF(szToolTip),TranslateT("SMS Confirmation from %s"),GetContactNameW(hContact));

				CLISTEVENT cle = { sizeof(cle) };
				cle.flags = CLEF_TCHAR;
				cle.hContact = hContact;
				cle.hDbEvent = hDbEvent;
				cle.hIcon = (HICON)LoadImage(ssSMSSettings.hInstance,MAKEINTRESOURCE(iIcon),IMAGE_ICON,0,0,LR_SHARED);
				cle.pszService = szServiceFunction;
				cle.ptszTooltip = szToolTip;
				CallService(MS_CLIST_ADDEVENT,0,(LPARAM)&cle);
			}
		}
	}
	MEMFREE(dbei.pBlob);
	return 0;
}
コード例 #15
0
LPSTR CExImContactBase::uid2String(BYTE bPrependType)
{
	CHAR szUID[MAX_PATH];
	LPSTR ptr = szUID;

	switch (_dbvUID.type) {
		case DBVT_BYTE:		//'b' bVal and cVal are valid
			if (bPrependType) *ptr++ = 'b';
			_itoa(_dbvUID.bVal, ptr, 10);
			break;
		case DBVT_WORD:		//'w' wVal and sVal are valid
			if (bPrependType) *ptr++ = 'w';
			_itoa(_dbvUID.wVal, ptr, 10);
			break;
		case DBVT_DWORD:	//'d' dVal and lVal are valid
			if (bPrependType) *ptr++ = 'd';
			_itoa(_dbvUID.dVal, ptr, 10);
			break;
		case DBVT_WCHAR:	//'u' pwszVal is valid
		{
			LPSTR r = mir_utf8encodeW(_dbvUID.pwszVal);
			if (bPrependType) {
				LPSTR t = (LPSTR)mir_alloc(strlen(r)+2);
				t[0] = 'u';
				strcpy(t+1, r);
				mir_free(r);
				r = t;
			}
			return r;
		}
		case DBVT_UTF8:		//'u' pszVal is valid
			{
				if (bPrependType) *ptr++ = 'u';
				mir_strncpy(ptr, _dbvUID.pszVal, SIZEOF(szUID)-1);
			}
			break;
		case DBVT_ASCIIZ: {
			LPSTR r = mir_utf8encode(_dbvUID.pszVal);
			if (bPrependType) {
				LPSTR t = (LPSTR)mir_alloc(strlen(r)+2);
				t[0] = 's';
				strcpy(t+1, r);
				mir_free(r);
				r = t;
			}
			return r;
		}
		case DBVT_BLOB:		//'n' cpbVal and pbVal are valid
		{
			if (bPrependType) {		//True = XML
				INT_PTR baselen = mir_base64_encode_bufsize(_dbvUID.cpbVal);
				LPSTR t = (LPSTR)mir_alloc(baselen + 5 + bPrependType);
				assert(t != NULL);
				if ( mir_base64_encodebuf(_dbvUID.pbVal, _dbvUID.cpbVal, t + bPrependType, baselen)) {
					t[baselen + bPrependType] = 0;
					if (bPrependType) t[0] = 'n';
					return t;
				}
				mir_free(t);
				return NULL;
			}
			else {		//FALSE = INI
				WORD j;
				INT_PTR baselen = (_dbvUID.cpbVal * 3);
				LPSTR t = (LPSTR)mir_alloc(3 + baselen);
				ZeroMemory(t, (3 + baselen));
				for (j = 0; j < _dbvUID.cpbVal; j++) {
					mir_snprintf((t + bPrependType + (j * 3)), 4,"%02X ", (BYTE)_dbvUID.pbVal[j]);
				}
				if (t){
					if (bPrependType) t[0] = 'n';
					return t;
				}
				else {
					mir_free(t);
					return NULL;
				}
			}
			break;
		}
		default:
			return NULL;
	}
	return mir_strdup(szUID);
}
コード例 #16
0
ファイル: dbini.cpp プロジェクト: MrtsComputers/miranda-ng
static void ProcessIniFile(TCHAR* szIniPath, char *szSafeSections, char *szUnsafeSections, int secur, bool secFN)
{
	FILE *fp = _tfopen(szIniPath, _T("rt"));
	if (fp == NULL)
		return;

	bool warnThisSection = false;
	char szSection[128]; szSection[0] = 0;

	while (!feof(fp)) {
		char szLine[2048];
		if (fgets(szLine, sizeof(szLine), fp) == NULL)
			break;
LBL_NewLine:
		int lineLength = lstrlenA(szLine);
		while (lineLength && (BYTE)(szLine[lineLength - 1]) <= ' ')
			szLine[--lineLength] = '\0';

		if (szLine[0] == ';' || szLine[0] <= ' ')
			continue;

		if (szLine[0] == '[') {
			char *szEnd = strchr(szLine + 1, ']');
			if (szEnd == NULL)
				continue;

			if (szLine[1] == '!')
				szSection[0] = '\0';
			else {
				lstrcpynA(szSection, szLine + 1, min(sizeof(szSection), (int)(szEnd - szLine)));
				switch (secur) {
				case 0:
					warnThisSection = false;
					break;

				case 1:
					warnThisSection = !IsInSpaceSeparatedList(szSection, szSafeSections);
					break;

				case 2:
					warnThisSection = IsInSpaceSeparatedList(szSection, szUnsafeSections);
					break;

				default:
					warnThisSection = true;
					break;
				}
				if (secFN) warnThisSection = 0;
			}
			if (szLine[1] == '?') {
				DBCONTACTENUMSETTINGS dbces;
				dbces.pfnEnumProc = SettingsEnumProc;
				lstrcpynA(szSection, szLine+2, min(sizeof(szSection), (int)(szEnd-szLine-1)));
				dbces.szModule = szSection;
				dbces.ofsSettings = 0;
				CallService(MS_DB_CONTACT_ENUMSETTINGS, 0, (LPARAM)&dbces);
				while (setting_items) {
					SettingsList *next = setting_items->next;

					db_unset(NULL, szSection, setting_items->name);

					mir_free(setting_items->name);
					mir_free(setting_items);
					setting_items = next;
				}
			}
			continue;
		}

		if (szSection[0] == '\0')
			continue;

		char *szValue = strchr(szLine, '=');
		if (szValue == NULL)
			continue;

		char szName[128];
		lstrcpynA(szName, szLine, min(sizeof(szName), (int)(szValue-szLine+1)));
		szValue++;
		{
			warnSettingChangeInfo_t warnInfo;
			warnInfo.szIniPath = szIniPath;
			warnInfo.szName = szName;
			warnInfo.szSafeSections = szSafeSections;
			warnInfo.szSection = szSection;
			warnInfo.szUnsafeSections = szUnsafeSections;
			warnInfo.szValue = szValue;
			warnInfo.warnNoMore = 0;
			warnInfo.cancel = 0;
			if (warnThisSection && IDNO == DialogBoxParam(hInst, MAKEINTRESOURCE(IDD_WARNINICHANGE), NULL, WarnIniChangeDlgProc, (LPARAM)&warnInfo))
				continue;
			if (warnInfo.cancel)
				break;
			if (warnInfo.warnNoMore)
				warnThisSection = 0;
		}

		switch (szValue[0]) {
		case 'b':
		case 'B':
			db_set_b(NULL, szSection, szName, (BYTE)strtol(szValue+1, NULL, 0));
			break;
		case 'w':
		case 'W':
			db_set_w(NULL, szSection, szName, (WORD)strtol(szValue+1, NULL, 0));
			break;
		case 'd':
		case 'D':
			db_set_dw(NULL, szSection, szName, (DWORD)strtoul(szValue+1, NULL, 0));
			break;
		case 'l':
		case 'L':
		case '-':
			db_unset(NULL, szSection, szName);
			break;
		case 'e':
		case 'E':
			ConvertBackslashes(szValue+1, Langpack_GetDefaultCodePage());
		case 's':
		case 'S':
			db_set_s(NULL, szSection, szName, szValue+1);
			break;
		case 'g':
		case 'G':
			for (char *pstr = szValue + 1; *pstr; pstr++) {
				if (*pstr == '\\') {
					switch (pstr[1]) {
					case 'n': *pstr = '\n'; break;
					case 't': *pstr = '\t'; break;
					case 'r': *pstr = '\r'; break;
					default:  *pstr = pstr[1]; break;
					}
					MoveMemory(pstr + 1, pstr + 2, lstrlenA(pstr + 2) + 1);
				}
			}
		case 'u':
		case 'U':
			db_set_utf(NULL, szSection, szName, szValue + 1);
			break;
		case 'm':
		case 'M':
			{
				CMStringA memo(szValue + 1);
				memo.Append("\r\n");
				while (fgets(szLine, sizeof(szLine), fp) != NULL) {
					switch (szLine[0]) {
					case 0: case '\r': case '\n': case ' ': case '\t':
						break;
					default:
						db_set_utf(NULL, szSection, szName, memo);
						goto LBL_NewLine;
					}

					memo.Append(rtrim(szLine + 1));
					memo.Append("\r\n");
				}
				db_set_utf(NULL, szSection, szName, memo);
			}
			break;
		case 'n':
		case 'h':
		case 'N':
		case 'H':
			{
				int len;
				char *pszValue, *pszEnd;

				PBYTE buf = (PBYTE)mir_alloc(lstrlenA(szValue + 1));
				for (len = 0, pszValue = szValue + 1;; len++) {
					buf[len] = (BYTE)strtol(pszValue, &pszEnd, 0x10);
					if (pszValue == pszEnd)
						break;
					pszValue = pszEnd;
				}
				db_set_blob(NULL, szSection, szName, buf, len);
				mir_free(buf);
			}
			break;
		default:
			TCHAR buf[250];
			mir_sntprintf(buf, SIZEOF(buf), TranslateT("Invalid setting type for '%s'. The first character of every value must be b, w, d, l, s, e, u, g, h or n."), _A2T(szName));
			MessageBox(NULL, buf, TranslateT("Install database settings"), MB_ICONWARNING | MB_OK);
			break;
		}
	}
	fclose(fp);
}
コード例 #17
0
bool gtcmtr_put(void)
{
	cm_region_list	*reg_ref;
	mval		v;
	unsigned char	buff[MAX_ZWR_KEY_SZ], *end;
	unsigned char	*ptr, regnum;
	short		n;
	unsigned short	top, len;
	static readonly gds_file_id file;

	error_def(ERR_KEY2BIG);
	error_def(ERR_REC2BIG);
	error_def(ERR_GVIS);
	error_def(ERR_DBPRIVERR);

	ptr = curr_entry->clb_ptr->mbf;
	assert(*ptr == CMMS_Q_PUT);
	ptr++;
	GET_USHORT(len, ptr);
	ptr += SIZEOF(unsigned short);
	regnum = *ptr++;
	reg_ref = gtcm_find_region(curr_entry,regnum);
	len--; /* subtract size of regnum */
	CM_GET_GVCURRKEY(ptr, len);
	gtcm_bind_name(reg_ref->reghead, TRUE);
	if (gv_cur_region->read_only)
		rts_error(VARLSTCNT(4) ERR_DBPRIVERR, 2, DB_LEN_STR(gv_cur_region));
	if (JNL_ALLOWED(cs_addrs))
	{	/* we need to copy client's specific prc_vec into the global variable in order that the gvcst* routines
		 *	do the right job. actually we need to do this only if JNL_ENABLED(cs_addrs), but since it is not
		 *	easy to re-execute the following two assignments in case gvcst_put()'s call to t_end() encounters a
		 *	cdb_sc_jnlstatemod retry code, we choose the easier approach of executing the following segment
		 *	if JNL_ALLOWED(cs_addrs) is TRUE instead of checking for JNL_ENABLED(cs_addrs) to be TRUE.
		 * this approach has the overhead that we will be doing the following assignments even though JNL_ENABLED
		 * 	might not be TRUE but since the following two are just pointer copies, it is not considered a big overhead.
		 * this approach ensures that the jnl_put_jrt_pini() gets the appropriate prc_vec for writing into the
		 * 	journal record in case JNL_ENABLED turns out to be TRUE in t_end() time.
		 * note that the value of JNL_ALLOWED(cs_addrs) cannot be changed on the fly without obtaining standalone access
		 * 	and hence the correctness of prc_vec (whenever it turns out necessary) is guaranteed.
		 */
		originator_prc_vec = curr_entry->pvec;
		cs_addrs->jnl->pini_addr = reg_ref->pini_addr;
	}
	GET_USHORT(len, ptr);
	ptr += SIZEOF(unsigned short);
	v.mvtype = MV_STR;
	v.str.len = len;
	v.str.addr = (char *)ptr;
	if ((n = gv_currkey->end + 1) > gv_cur_region->max_key_size)
	{
		if ((end = format_targ_key(&buff[0], MAX_ZWR_KEY_SZ, gv_currkey, TRUE)) == 0)
			end = &buff[MAX_ZWR_KEY_SZ - 1];
		rts_error(VARLSTCNT(11) ERR_KEY2BIG, 4, n, (int4)gv_cur_region->max_key_size,
			REG_LEN_STR(gv_cur_region), 0, ERR_GVIS, 2, end - buff, buff);
	}
	if (n + v.str.len + SIZEOF(rec_hdr) > gv_cur_region->max_rec_size)
	{
		if ((end = format_targ_key(&buff[0], MAX_ZWR_KEY_SZ, gv_currkey, TRUE)) == 0)
			end = &buff[MAX_ZWR_KEY_SZ - 1];
		rts_error(VARLSTCNT(10) ERR_REC2BIG, 4, n + v.str.len + SIZEOF(rec_hdr),
			(int4)gv_cur_region->max_rec_size, REG_LEN_STR(gv_cur_region),
			ERR_GVIS, 2, end - buff, buff);
	}
	gvcst_put(&v);
	if (JNL_ALLOWED(cs_addrs))
		reg_ref->pini_addr = cs_addrs->jnl->pini_addr; /* In case  journal switch occurred */
	ptr = curr_entry->clb_ptr->mbf;
	*ptr++ = CMMS_R_PUT;
	curr_entry->clb_ptr->cbl = S_HDRSIZE;
	return TRUE;
}
コード例 #18
0
ファイル: dbini.cpp プロジェクト: MrtsComputers/miranda-ng
static void DoAutoExec(void)
{
	TCHAR szUse[7], szIniPath[MAX_PATH], szFindPath[MAX_PATH];
	TCHAR buf[2048], szSecurity[11], szOverrideSecurityFilename[MAX_PATH], szOnCreateFilename[MAX_PATH];
	char *szSafeSections, *szUnsafeSections;
	int secur;

	GetPrivateProfileString(_T("AutoExec"), _T("Use"), _T("prompt"), szUse, SIZEOF(szUse), mirandabootini);
	if (!lstrcmpi(szUse, _T("no"))) return;
	GetPrivateProfileString(_T("AutoExec"), _T("Safe"), _T("CLC Icons CLUI CList SkinSounds PluginUpdater"), buf, SIZEOF(buf), mirandabootini);
	szSafeSections = mir_t2a(buf);
	GetPrivateProfileString(_T("AutoExec"), _T("Unsafe"), _T("AIM Facebook GG ICQ IRC JABBER MRA MSN SKYPE Tlen TWITTER XFire"), buf, SIZEOF(buf), mirandabootini);
	szUnsafeSections = mir_t2a(buf);
	GetPrivateProfileString(_T("AutoExec"), _T("Warn"), _T("notsafe"), szSecurity, SIZEOF(szSecurity), mirandabootini);
	if (!lstrcmpi(szSecurity, _T("none"))) secur = 0;
	else if (!lstrcmpi(szSecurity, _T("notsafe"))) secur = 1;
	else if (!lstrcmpi(szSecurity, _T("onlyunsafe"))) secur = 2;

	GetPrivateProfileString(_T("AutoExec"), _T("OverrideSecurityFilename"), _T(""), szOverrideSecurityFilename, SIZEOF(szOverrideSecurityFilename), mirandabootini);
	GetPrivateProfileString(_T("AutoExec"), _T("OnCreateFilename"), _T(""), szOnCreateFilename, SIZEOF(szOnCreateFilename), mirandabootini);
	GetPrivateProfileString(_T("AutoExec"), _T("Glob"), _T("autoexec_*.ini"), szFindPath, SIZEOF(szFindPath), mirandabootini);

	if (g_bDbCreated && szOnCreateFilename[0]) {
		PathToAbsoluteT(VARST(szOnCreateFilename), szIniPath);
		ProcessIniFile(szIniPath, szSafeSections, szUnsafeSections, 0, 1);
	}

	PathToAbsoluteT(VARST(szFindPath), szFindPath);

	WIN32_FIND_DATA fd;
	HANDLE hFind = FindFirstFile(szFindPath, &fd);
	if (hFind == INVALID_HANDLE_VALUE) {
		mir_free(szSafeSections);
		mir_free(szUnsafeSections);
		return;
	}

	TCHAR *str2 = _tcsrchr(szFindPath, '\\');
	if (str2 == NULL) szFindPath[0] = 0;
	else str2[1] = 0;

	do {
		bool secFN = lstrcmpi(fd.cFileName, szOverrideSecurityFilename) == 0;

		mir_sntprintf(szIniPath, SIZEOF(szIniPath), _T("%s%s"), szFindPath, fd.cFileName);
		if (!lstrcmpi(szUse, _T("prompt")) && !secFN) {
			int result = DialogBoxParam(hInst, MAKEINTRESOURCE(IDD_INSTALLINI), NULL, InstallIniDlgProc, (LPARAM)szIniPath);
			if (result == IDC_NOTOALL) break;
			if (result == IDCANCEL) continue;
		}

		ProcessIniFile(szIniPath, szSafeSections, szUnsafeSections, secur, secFN);

		if (secFN)
			DeleteFile(szIniPath);
		else {
			TCHAR szOnCompletion[8];
			GetPrivateProfileString(_T("AutoExec"), _T("OnCompletion"), _T("recycle"), szOnCompletion, SIZEOF(szOnCompletion), mirandabootini);
			if (!lstrcmpi(szOnCompletion, _T("delete")))
				DeleteFile(szIniPath);
			else if (!lstrcmpi(szOnCompletion, _T("recycle"))) {
				SHFILEOPSTRUCT shfo = { 0 };
				shfo.wFunc = FO_DELETE;
				shfo.pFrom = szIniPath;
				szIniPath[lstrlen(szIniPath) + 1] = 0;
				shfo.fFlags = FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT | FOF_ALLOWUNDO;
				SHFileOperation(&shfo);
			}
			else if (!lstrcmpi(szOnCompletion, _T("rename"))) {
				TCHAR szRenamePrefix[MAX_PATH];
				TCHAR szNewPath[MAX_PATH];
				GetPrivateProfileString(_T("AutoExec"), _T("RenamePrefix"), _T("done_"), szRenamePrefix, SIZEOF(szRenamePrefix), mirandabootini);
				lstrcpy(szNewPath, szFindPath);
				lstrcat(szNewPath, szRenamePrefix);
				lstrcat(szNewPath, fd.cFileName);
				MoveFile(szIniPath, szNewPath);
			}
			else if (!lstrcmpi(szOnCompletion, _T("ask")))
				DialogBoxParam(hInst, MAKEINTRESOURCE(IDD_INIIMPORTDONE), NULL, IniImportDoneDlgProc, (LPARAM)szIniPath);
		}
	}
		while (FindNextFile(hFind, &fd));

	FindClose(hFind);
	mir_free(szSafeSections);
	mir_free(szUnsafeSections);
}
コード例 #19
0
ファイル: mu_rndwn_all.c プロジェクト: ChristyV/fis-gtm
/* Takes an entry from 'ipcs -am' and checks for its validity to be a GT.M replication segment.
 * Returns TRUE if the shared memory segment is a valid GT.M replication segment
 * (based on a check on some fields in the shared memory) else FALSE.
 * If the segment belongs to GT.M, it returns the replication id of the segment
 * by the second argument.
 * Sets exit_stat to ERR_MUNOTALLSEC if appropriate.
 */
boolean_t validate_replpool_shm_entry(shm_parms *parm_buff, replpool_id_ptr_t replpool_id, int *exit_stat)
{
	boolean_t		remove_shmid, jnlpool_segment;
	int			fd;
	repl_inst_hdr		repl_instance;
	sm_uc_ptr_t		start_addr;
	int			save_errno, status, shmid;
	struct shmid_ds		shmstat;
	char			msgbuff[OUT_BUFF_SIZE], *instfilename;

	if (NULL == parm_buff)
		return FALSE;
	/* Check for the bare minimum size of the replic shared segment that we expect */
	/* if (parm_buff->sgmnt_siz < (SIZEOF(replpool_identifier) + MIN(MIN_JNLPOOL_SIZE, MIN_RECVPOOL_SIZE))) */
	if (parm_buff->sgmnt_siz < MIN(MIN_JNLPOOL_SIZE, MIN_RECVPOOL_SIZE))
		return FALSE;
	if (IPC_PRIVATE != parm_buff->key)
		return FALSE;
	shmid = parm_buff->shmid;
	/* we do not need to lock the shm for reading the rundown information as
	 * the other rundowns (if any) can also be allowed to share reading the
	 * same info concurrently.
	 */
	if (-1 == (sm_long_t)(start_addr = (sm_uc_ptr_t) do_shmat(shmid, 0, SHM_RND)))
		return FALSE;
	memcpy((void *)replpool_id, (void *)start_addr, SIZEOF(replpool_identifier));
	instfilename = replpool_id->instfilename;
	/* Even though we could be looking at a replication pool structure that has been created by an older version
	 * or newer version of GT.M, the format of the "replpool_identifier" structure is expected to be the same
	 * across all versions so we can safely dereference the "label" and "instfilename" fields in order to generate
	 * user-friendly error messages. Asserts for the layout are in "mu_rndwn_repl_instance" (not here) with a
	 * comment there as to why that location was chosen.
	 */
	if (memcmp(replpool_id->label, GDS_RPL_LABEL, GDS_LABEL_SZ - 1))
	{
		if (!memcmp(replpool_id->label, GDS_RPL_LABEL, GDS_LABEL_SZ - 3))
		{
			util_out_print("Cannot rundown replpool shmid = !UL as it has format !AD "
				"created by !AD but this mupip is version and uses format !AD",
				TRUE, shmid, GDS_LABEL_SZ - 1, replpool_id->label,
				LEN_AND_STR(replpool_id->now_running), gtm_release_name_len, gtm_release_name,
				GDS_LABEL_SZ - 1, GDS_RPL_LABEL);
			*exit_stat = ERR_MUNOTALLSEC;
		}
		shmdt((void *)start_addr);
		return FALSE;
	}
	assert(JNLPOOL_SEGMENT == replpool_id->pool_type || RECVPOOL_SEGMENT == replpool_id->pool_type);
	if(JNLPOOL_SEGMENT != replpool_id->pool_type && RECVPOOL_SEGMENT != replpool_id->pool_type)
	{
		shmdt((void *)start_addr);
		return FALSE;
	}
	jnlpool_segment = (JNLPOOL_SEGMENT == replpool_id->pool_type);
	if (-1 == shmctl(shmid, IPC_STAT, &shmstat))
	{
		save_errno = errno;
		assert(FALSE);/* we were able to attach to this shmid before so should be able to get stats on it */
		util_out_print("!AD -> Error with shmctl for shmid = !UL",
				TRUE, LEN_AND_STR(instfilename), shmid);
		gtm_putmsg(VARLSTCNT(1) save_errno);
		*exit_stat = ERR_MUNOTALLSEC;
		shmdt((void *)start_addr);
		return FALSE;
	}
	/* Check if instance filename reported in shared memory still exists. If not, clean this
	 * shared memory section without even invoking "mu_rndwn_repl_instance" as that expects
	 * the instance file to exist. Same case if shared memory points back to an instance file
	 * whose file header does not have this shmid.
	 */
	OPENFILE(instfilename, O_RDONLY, fd);	/* check if we can open it */
	msgbuff[0] = '\0';
	remove_shmid = FALSE;
	if (FD_INVALID == fd)
	{
		if (ENOENT == errno)
		{
			SNPRINTF(msgbuff, OUT_BUFF_SIZE, "File %s does not exist", instfilename);
			if (1 < shmstat.shm_nattch)
			{
				PRINT_AND_SEND_REPLPOOL_FAILURE_MSG(msgbuff, replpool_id, shmid);
				*exit_stat = ERR_MUNOTALLSEC;
				shmdt((void *)start_addr);
				return FALSE;
			}
			remove_shmid = TRUE;
		} else
		{	/* open() errored out e.g. due to file permissions. Log that */
			save_errno = errno;
			util_out_print("Cannot rundown replpool shmid !UL for instance file"
				" !AD as open() on the file returned the following error",
				TRUE, shmid, LEN_AND_STR(instfilename));
			gtm_putmsg(VARLSTCNT(1) save_errno);
			*exit_stat = ERR_MUNOTALLSEC;
			shmdt((void *)start_addr);
			return FALSE;
		}
	} else
	{
		LSEEKREAD(fd, 0, &repl_instance, SIZEOF(repl_inst_hdr), status);
		if (0 != status)
		{
			save_errno = errno;
			util_out_print("!AD -> Error with LSEEKREAD for shmid = !UL", TRUE,
				LEN_AND_STR(instfilename), shmid);
			gtm_putmsg(VARLSTCNT(1) save_errno);
			*exit_stat = ERR_MUNOTALLSEC;
			shmdt((void *)start_addr);
			return FALSE;
		}
		if ((jnlpool_segment && (repl_instance.jnlpool_shmid != shmid))
			|| (!jnlpool_segment && (repl_instance.recvpool_shmid != shmid)))
		{
			SNPRINTF(msgbuff, OUT_BUFF_SIZE, "%s SHMID (%d) in the instance file header does not match with the"
					" one reported by \"ipcs\" command (%d)", jnlpool_segment ? "Journal Pool" : "Receive Pool",
					jnlpool_segment ? repl_instance.jnlpool_shmid : repl_instance.recvpool_shmid, shmid);
			if (1 < shmstat.shm_nattch)
			{
				PRINT_AND_SEND_REPLPOOL_FAILURE_MSG(msgbuff, replpool_id, shmid);
				*exit_stat = ERR_MUNOTALLSEC;
				shmdt((void *)start_addr);
				return FALSE;
			}
			remove_shmid = TRUE;
		}
		CLOSEFILE_RESET(fd, status);	/* resets "fd" to FD_INVALID */
	}
	shmdt((void *)start_addr);
	if (remove_shmid)
	{
		assert('\0' != msgbuff[0]);
		if (0 != shm_rmid(shmid))
		{
			save_errno = errno;
			util_out_print("!AD -> Error removing shared memory for shmid = !UL",
				TRUE, LEN_AND_STR(instfilename), shmid);
			gtm_putmsg(VARLSTCNT(1) save_errno);
			*exit_stat = ERR_MUNOTALLSEC;
			return FALSE;
		}
		PRINT_AND_SEND_SHMREMOVED_MSG(msgbuff, STRLEN(instfilename), instfilename, shmid);
		*exit_stat = ERR_SHMREMOVED;
	} else
		*exit_stat = SS_NORMAL;
	return TRUE;
}
コード例 #20
0
ファイル: write_entry.c プロジェクト: BA3IK/node-ncurses
static int
write_object(TERMTYPE *tp, char *buffer, unsigned *offset, unsigned limit)
{
    char *namelist;
    size_t namelen, boolmax, nummax, strmax;
    char zero = '\0';
    size_t i;
    int nextfree;
    short offsets[MAX_ENTRY_SIZE / 2];
    unsigned char buf[MAX_ENTRY_SIZE];
    unsigned last_bool = BOOLWRITE;
    unsigned last_num = NUMWRITE;
    unsigned last_str = STRWRITE;

#if NCURSES_XNAMES
    /*
     * Normally we limit the list of values to exclude the "obsolete"
     * capabilities.  However, if we are accepting extended names, add
     * these as well, since they are used for supporting translation
     * to/from termcap.
     */
    if (_nc_user_definable) {
	last_bool = BOOLCOUNT;
	last_num = NUMCOUNT;
	last_str = STRCOUNT;
    }
#endif

    namelist = tp->term_names;
    namelen = strlen(namelist) + 1;

    boolmax = 0;
    for (i = 0; i < last_bool; i++) {
	if (tp->Booleans[i] == TRUE)
	    boolmax = i + 1;
    }

    nummax = 0;
    for (i = 0; i < last_num; i++) {
	if (tp->Numbers[i] != ABSENT_NUMERIC)
	    nummax = i + 1;
    }

    strmax = 0;
    for (i = 0; i < last_str; i++) {
	if (tp->Strings[i] != ABSENT_STRING)
	    strmax = i + 1;
    }

    nextfree = compute_offsets(tp->Strings, strmax, offsets);

    /* fill in the header */
    LITTLE_ENDIAN(buf, MAGIC);
    LITTLE_ENDIAN(buf + 2, min(namelen, MAX_NAME_SIZE + 1));
    LITTLE_ENDIAN(buf + 4, boolmax);
    LITTLE_ENDIAN(buf + 6, nummax);
    LITTLE_ENDIAN(buf + 8, strmax);
    LITTLE_ENDIAN(buf + 10, nextfree);

    /* write out the header */
    TRACE_OUT(("Header of %s @%d", namelist, *offset));
    if (Write(buf, 12, 1) != 1
	|| Write(namelist, sizeof(char), namelen) != namelen)
	  return (ERR);

    for (i = 0; i < boolmax; i++)
	if (tp->Booleans[i] == TRUE)
	    buf[i] = TRUE;
	else
	    buf[i] = FALSE;
    if (Write(buf, sizeof(char), boolmax) != boolmax)
	  return (ERR);

    if (even_boundary(namelen + boolmax))
	return (ERR);

    TRACE_OUT(("Numerics begin at %04x", *offset));

    /* the numerics */
    convert_shorts(buf, tp->Numbers, nummax);
    if (Write(buf, 2, nummax) != nummax)
	return (ERR);

    TRACE_OUT(("String offsets begin at %04x", *offset));

    /* the string offsets */
    convert_shorts(buf, offsets, strmax);
    if (Write(buf, 2, strmax) != strmax)
	return (ERR);

    TRACE_OUT(("String table begins at %04x", *offset));

    /* the strings */
    for (i = 0; i < strmax; i++)
	if (VALID_STRING(tp->Strings[i]))
	    if (!WRITE_STRING(tp->Strings[i]))
		return (ERR);

#if NCURSES_XNAMES
    if (extended_object(tp)) {
	unsigned extcnt = (unsigned) NUM_EXT_NAMES(tp);

	if (even_boundary(nextfree))
	    return (ERR);

	nextfree = compute_offsets(tp->Strings + STRCOUNT,
				   (size_t) tp->ext_Strings,
				   offsets);
	TRACE_OUT(("after extended string capabilities, nextfree=%d", nextfree));

	if (tp->ext_Strings >= SIZEOF(offsets))
	    return (ERR);

	nextfree += compute_offsets(tp->ext_Names,
				    (size_t) extcnt,
				    offsets + tp->ext_Strings);
	TRACE_OUT(("after extended capnames, nextfree=%d", nextfree));
	strmax = tp->ext_Strings + extcnt;

	/*
	 * Write the extended header
	 */
	LITTLE_ENDIAN(buf + 0, tp->ext_Booleans);
	LITTLE_ENDIAN(buf + 2, tp->ext_Numbers);
	LITTLE_ENDIAN(buf + 4, tp->ext_Strings);
	LITTLE_ENDIAN(buf + 6, strmax);
	LITTLE_ENDIAN(buf + 8, nextfree);
	TRACE_OUT(("WRITE extended-header @%d", *offset));
	if (Write(buf, 10, 1) != 1)
	    return (ERR);

	TRACE_OUT(("WRITE %d booleans @%d", tp->ext_Booleans, *offset));
	if (tp->ext_Booleans
	    && Write(tp->Booleans + BOOLCOUNT, sizeof(char),
		     tp->ext_Booleans) != tp->ext_Booleans)
	      return (ERR);

	if (even_boundary(tp->ext_Booleans))
	    return (ERR);

	TRACE_OUT(("WRITE %d numbers @%d", tp->ext_Numbers, *offset));
	if (tp->ext_Numbers) {
	    convert_shorts(buf, tp->Numbers + NUMCOUNT, (size_t) tp->ext_Numbers);
	    if (Write(buf, 2, tp->ext_Numbers) != tp->ext_Numbers)
		return (ERR);
	}

	/*
	 * Convert the offsets for the ext_Strings and ext_Names tables,
	 * in that order.
	 */
	convert_shorts(buf, offsets, strmax);
	TRACE_OUT(("WRITE offsets @%d", *offset));
	if (Write(buf, 2, strmax) != strmax)
	    return (ERR);

	/*
	 * Write the string table after the offset tables so we do not
	 * have to do anything about alignment.
	 */
	for (i = 0; i < tp->ext_Strings; i++) {
	    if (VALID_STRING(tp->Strings[i + STRCOUNT])) {
		TRACE_OUT(("WRITE ext_Strings[%d]=%s", (int) i,
			   _nc_visbuf(tp->Strings[i + STRCOUNT])));
		if (!WRITE_STRING(tp->Strings[i + STRCOUNT]))
		    return (ERR);
	    }
	}

	/*
	 * Write the extended names
	 */
	for (i = 0; i < extcnt; i++) {
	    TRACE_OUT(("WRITE ext_Names[%d]=%s", (int) i, tp->ext_Names[i]));
	    if (!WRITE_STRING(tp->ext_Names[i]))
		return (ERR);
	}

    }
#endif /* NCURSES_XNAMES */

    total_written++;
    return (OK);
}
コード例 #21
0
ファイル: clisttray.cpp プロジェクト: martok/miranda-ng
int fnTrayIconUpdate(HICON hNewIcon, const TCHAR *szNewTip, const char *szPreferredProto, int isBase)
{
	initcheck - 1;
	mir_cslock lck(trayLockCS);

	NOTIFYICONDATA nid = { SIZEOFNID };
	nid.hWnd = cli.hwndContactList;
	nid.uFlags = NIF_ICON | NIF_TIP;
	nid.hIcon = hNewIcon;
	if (!hNewIcon)
		return -1;

	for (int i = 0; i < cli.trayIconCount; i++) {
		if (cli.trayIcon[i].id == 0)
			continue;
		if (mir_strcmp(cli.trayIcon[i].szProto, szPreferredProto))
			continue;

		nid.uID = cli.trayIcon[i].id;
		cli.pfnTrayIconMakeTooltip(szNewTip, cli.trayIcon[i].szProto);
		mir_free(cli.trayIcon[i].ptszToolTip);
		cli.trayIcon[i].ptszToolTip = mir_tstrdup(cli.szTip);
		if (!mToolTipTrayTips)
			mir_tstrncpy(nid.szTip, cli.szTip, SIZEOF(nid.szTip));
		Shell_NotifyIcon(NIM_MODIFY, &nid);

		if (cli.trayIconCount == 1)
			SetTaskBarIcon(hNewIcon, cli.szTip);
		else
			SetTaskBarIcon(NULL, NULL);

		cli.trayIcon[i].isBase = isBase;
		return i;
	}

	// if there wasn't a suitable icon, change all the icons
	for (int i = 0; i < cli.trayIconCount; i++) {
		if (cli.trayIcon[i].id == 0)
			continue;
		nid.uID = cli.trayIcon[i].id;

		cli.pfnTrayIconMakeTooltip(szNewTip, cli.trayIcon[i].szProto);
		mir_free(cli.trayIcon[i].ptszToolTip);
		cli.trayIcon[i].ptszToolTip = mir_tstrdup(cli.szTip);
		if (!mToolTipTrayTips)
			mir_tstrncpy(nid.szTip, cli.szTip, SIZEOF(nid.szTip));
		Shell_NotifyIcon(NIM_MODIFY, &nid);

		if (cli.trayIconCount == 1)
			SetTaskBarIcon(hNewIcon, cli.szTip);
		else
			SetTaskBarIcon(NULL, NULL);

		cli.trayIcon[i].isBase = isBase;
		if (db_get_b(NULL, "CList", "TrayIcon", SETTING_TRAYICON_DEFAULT) == SETTING_TRAYICON_MULTI) {
			DWORD time1 = db_get_w(NULL, "CList", "CycleTime", SETTING_CYCLETIME_DEFAULT) * 200;
			DWORD time2 = db_get_w(NULL, "CList", "IconFlashTime", 550) + 1000;
			DWORD time = max(max(2000, time1), time2);
			if (RefreshTimerId)
				KillTimer(NULL, RefreshTimerId);

			// if unknown base was changed - than show preffered proto icon for 2 sec
			// and reset it to original one after timeout
			RefreshTimerId = SetTimer(NULL, 0, time, RefreshTimerProc);
		}
		return i;
	}

	return -1;
}
コード例 #22
0
/*
 * This will rundown a replication instance journal (and receiver) pool.
 *	Input Parameter:
 *		replpool_id of the instance. Instance file name must be null terminated in replpool_id.
 * Returns :
 *	TRUE,  if successful.
 *	FALSE, otherwise.
 */
boolean_t mu_rndwn_repl_instance(replpool_identifier *replpool_id, boolean_t immediate, boolean_t rndwn_both_pools,
					boolean_t *jnlpool_sem_created)
{
	boolean_t		jnlpool_stat = SS_NORMAL, recvpool_stat = SS_NORMAL, decr_cnt, sem_created = FALSE, ipc_rmvd;
	char			*instfilename;
	unsigned char		ipcs_buff[MAX_IPCS_ID_BUF], *ipcs_ptr;
	gd_region		*r_save;
	repl_inst_hdr		repl_instance;
	static	gd_region	*reg = NULL;
	struct semid_ds		semstat;
	struct shmid_ds		shmstat;
	unix_db_info		*udi;
	int			save_errno, sem_id, shm_id, status;
	sgmnt_addrs		*repl_csa;
	boolean_t		was_crit, remove_sem;
	DCL_THREADGBL_ACCESS;

	SETUP_THREADGBL_ACCESS;
	if (NULL == reg)
	{
		r_save = gv_cur_region;
		mu_gv_cur_reg_init();
		reg = gv_cur_region;
		gv_cur_region = r_save;
	}
	*jnlpool_sem_created = FALSE;
	/* Assert that the layout of replpool_identifier is identical for all versions going forward as the function
	 * "validate_replpool_shm_entry" (used by the argumentless mupip rundown aka "mupip rundown") relies on this.
	 * This assert is placed here (instead of there) because the automated tests exercise this logic much more
	 * than the argumentless code. If any of these asserts fail, "validate_replpool_shm_entry" needs to change
	 * to handle the old and new layouts.
	 *
	 *	Structure ----> replpool_identifier <----    size 312 [0x0138]
	 *
	 *		offset = 0000 [0x0000]      size = 0012 [0x000c]    ----> replpool_identifier.label
	 *		offset = 0012 [0x000c]      size = 0001 [0x0001]    ----> replpool_identifier.pool_type
	 *		offset = 0013 [0x000d]      size = 0036 [0x0024]    ----> replpool_identifier.now_running
	 *		offset = 0052 [0x0034]      size = 0004 [0x0004]    ----> replpool_identifier.repl_pool_key_filler
	 *		offset = 0056 [0x0038]      size = 0256 [0x0100]    ----> replpool_identifier.instfilename
	 */
	assert(0 == OFFSETOF(replpool_identifier, label[0]));
	assert(12 == SIZEOF(((replpool_identifier *)NULL)->label));
	assert(12 == OFFSETOF(replpool_identifier, pool_type));
	assert(1 == SIZEOF(((replpool_identifier *)NULL)->pool_type));
	assert(13 == OFFSETOF(replpool_identifier, now_running[0]));
	assert(36 == SIZEOF(((replpool_identifier *)NULL)->now_running));
	assert(56 == OFFSETOF(replpool_identifier, instfilename[0]));
	assert(256 == SIZEOF(((replpool_identifier *)NULL)->instfilename));
	/* End asserts */
	jnlpool.jnlpool_dummy_reg = reg;
	recvpool.recvpool_dummy_reg = reg;
	instfilename = replpool_id->instfilename;
	reg->dyn.addr->fname_len = strlen(instfilename);
	assert(0 == instfilename[reg->dyn.addr->fname_len]);
	memcpy((char *)reg->dyn.addr->fname, instfilename, reg->dyn.addr->fname_len + 1);
	udi = FILE_INFO(reg);
	udi->fn = (char *)reg->dyn.addr->fname;
	/* Lock replication instance using ftok semaphore so that no other replication process can startup until we are done with
	 * rundown
	 */
	if (!ftok_sem_get(reg, TRUE, REPLPOOL_ID, immediate))
		return FALSE;
	ESTABLISH_RET(mu_rndwn_repl_instance_ch, FALSE);
	repl_inst_read(instfilename, (off_t)0, (sm_uc_ptr_t)&repl_instance, SIZEOF(repl_inst_hdr));
	assert(rndwn_both_pools || JNLPOOL_SEGMENT == replpool_id->pool_type || RECVPOOL_SEGMENT == replpool_id->pool_type);
	if (rndwn_both_pools || (JNLPOOL_SEGMENT == replpool_id->pool_type))
	{	/* --------------------------
		 * First rundown Journal pool
		 * --------------------------
		 */
		shm_id = repl_instance.jnlpool_shmid;
		if (SS_NORMAL == (jnlpool_stat = mu_replpool_grab_sem(&repl_instance, JNLPOOL_SEGMENT, &sem_created, immediate)))
		{
			/* Got JNL_POOL_ACCESS_SEM and incremented SRC_SRV_COUNT_SEM */
			assert(holds_sem[SOURCE][JNL_POOL_ACCESS_SEM]);
			assert(holds_sem[SOURCE][SRC_SERV_COUNT_SEM]);
			sem_id = repl_instance.jnlpool_semid;
			if ((INVALID_SHMID == shm_id) || (-1 == shmctl(shm_id, IPC_STAT, &shmstat))
				|| (shmstat.shm_ctime != repl_instance.jnlpool_shmid_ctime))
			{
				repl_instance.jnlpool_shmid = shm_id = INVALID_SHMID;
				repl_instance.jnlpool_shmid_ctime = 0;
			}
			assert((INVALID_SHMID != shm_id) || ((NULL == jnlpool.jnlpool_ctl) && (NULL == jnlpool_ctl)));
			ipc_rmvd = TRUE;
			if (INVALID_SHMID != shm_id)
			{
				replpool_id->pool_type = JNLPOOL_SEGMENT;
				jnlpool_stat = mu_rndwn_replpool(replpool_id, &repl_instance, shm_id, &ipc_rmvd);
				ipcs_ptr = i2asc((uchar_ptr_t)ipcs_buff, shm_id);
				*ipcs_ptr = '\0';
				if (rndwn_both_pools && ((SS_NORMAL != jnlpool_stat) || ipc_rmvd))
					gtm_putmsg_csa(CSA_ARG(NULL) VARLSTCNT(6)
							(jnlpool_stat ? ERR_MUJPOOLRNDWNFL : ERR_MUJPOOLRNDWNSUC),
							4, LEN_AND_STR(ipcs_buff), LEN_AND_STR(instfilename));
			}
			assert(ipc_rmvd || (NULL != jnlpool_ctl));
			assert((NULL == jnlpool.jnlpool_ctl) || (SS_NORMAL == jnlpool_stat) || jgbl.onlnrlbk);
			assert((INVALID_SHMID != repl_instance.jnlpool_shmid) || (0 == repl_instance.jnlpool_shmid_ctime));
			assert((INVALID_SHMID == repl_instance.jnlpool_shmid) || (0 != repl_instance.jnlpool_shmid_ctime));
			assert(INVALID_SEMID != sem_id);
			if (!mur_options.rollback)
			{	/* Invoked by MUPIP RUNDOWN in which case the semaphores needs to be removed. But, remove the
				 * semaphore ONLY if we created it here OR the journal pool was successfully removed.
				 */
				if (NULL == jnlpool_ctl)
				{
					remove_sem = sem_created || (SS_NORMAL == jnlpool_stat);
					if (!remove_sem)
						add_to_semids_list(repl_instance.jnlpool_semid);
					status = mu_replpool_release_sem(&repl_instance, JNLPOOL_SEGMENT, remove_sem);
					if ((SS_NORMAL == status) && remove_sem)
					{	/* Now that semaphores are removed, reset fields in file header */
						if (!sem_created)
						{	/* If sem_id was created by mu_replpool_grab_sem then do NOT report the
							 * MURPOOLRNDWNSUC message as it indicates that the semaphore was orphaned
							 * and we removed it when in fact there was no orphaned semaphore and we
							 * created it as part of mu_replpool_grab_sem to get standalone access to
							 * rundown the receiver pool (which may or may not exist)
							 */
							ipcs_ptr = i2asc((uchar_ptr_t)ipcs_buff, sem_id);
							*ipcs_ptr = '\0';
							gtm_putmsg_csa(CSA_ARG(NULL) VARLSTCNT(9) ERR_MUJPOOLRNDWNSUC, 4,
									LEN_AND_STR(ipcs_buff),
									LEN_AND_STR(instfilename), ERR_SEMREMOVED, 1, sem_id);
						}
						repl_inst_jnlpool_reset();
					}
				} else
				{	/* Anticipatory Freeze scheme is turned ON. So, release just the JNL_POOL_ACCESS_SEM. The
					 * semaphore will be released/removed in the caller (mupip_rundown)
					 */
					assert(INST_FREEZE_ON_ERROR_POLICY);
					assertpro(SS_NORMAL == (status = rel_sem(SOURCE, JNL_POOL_ACCESS_SEM)));
					assert(!holds_sem[SOURCE][JNL_POOL_ACCESS_SEM]);
					/* Since we are not resetting the semaphore IDs in the file header, we need to write out
					 * the semaphore IDs in the instance file (if we created them).
					 */
					if (sem_created)
						repl_inst_write(instfilename, (off_t)0, (sm_uc_ptr_t)&repl_instance,
									SIZEOF(repl_inst_hdr));
				}
			}
		} else if (rndwn_both_pools && (INVALID_SHMID != shm_id))
		{
			ipcs_ptr = i2asc((uchar_ptr_t)ipcs_buff, shm_id);
			*ipcs_ptr = '\0';
			if (rndwn_both_pools)
				gtm_putmsg_csa(CSA_ARG(NULL) VARLSTCNT(6) ERR_MUJPOOLRNDWNFL, 4, LEN_AND_STR(ipcs_buff),
					LEN_AND_STR(instfilename));
		}
		*jnlpool_sem_created = sem_created;
	}
	if (((SS_NORMAL == jnlpool_stat) || !jgbl.mur_rollback) &&
		(rndwn_both_pools || (RECVPOOL_SEGMENT == replpool_id->pool_type)))
	{	/* --------------------------
		 * Now rundown Receivpool
		 * --------------------------
		 * Note: RECVPOOL is rundown ONLY if the JNLPOOL rundown was successful. This way, we don't end up
		 * creating new semaphores for the RECVPOOL if ROLLBACK is not going to start anyways because of the failed
		 * JNLPOOL rundown. The only exception is MUPIP RUNDOWN command in which case we try running down the
		 * RECVPOOL even if the JNLPOOL rundown failed.
		 */
		shm_id = repl_instance.recvpool_shmid;
		if (SS_NORMAL == (recvpool_stat = mu_replpool_grab_sem(&repl_instance, RECVPOOL_SEGMENT, &sem_created, immediate)))
		{
			sem_id = repl_instance.recvpool_semid;
			if ((INVALID_SHMID == shm_id) || (-1 == shmctl(shm_id, IPC_STAT, &shmstat))
				|| (shmstat.shm_ctime != repl_instance.recvpool_shmid_ctime))
			{
				repl_instance.recvpool_shmid = shm_id = INVALID_SHMID;
				repl_instance.recvpool_shmid_ctime = 0;
			}
			ipc_rmvd = TRUE;
			if (INVALID_SHMID != shm_id)
			{
				replpool_id->pool_type = RECVPOOL_SEGMENT;
				recvpool_stat = mu_rndwn_replpool(replpool_id, &repl_instance, shm_id, &ipc_rmvd);
				ipcs_ptr = i2asc((uchar_ptr_t)ipcs_buff, shm_id);
				*ipcs_ptr = '\0';
				if (rndwn_both_pools && ((SS_NORMAL != recvpool_stat) || ipc_rmvd))
					gtm_putmsg_csa(CSA_ARG(NULL) VARLSTCNT(6)
							(recvpool_stat ? ERR_MURPOOLRNDWNFL : ERR_MURPOOLRNDWNSUC),
							4, LEN_AND_STR(ipcs_buff), LEN_AND_STR(instfilename));
			}
			assert((TRUE == ipc_rmvd) || (SS_NORMAL != recvpool_stat) || jgbl.onlnrlbk);
			assert((INVALID_SHMID != repl_instance.recvpool_shmid) || (0 == repl_instance.recvpool_shmid_ctime));
			assert((INVALID_SHMID == repl_instance.recvpool_shmid) || (0 != repl_instance.recvpool_shmid_ctime));
			assert(INVALID_SEMID != sem_id);
			if (!mur_options.rollback)
			{	/* Invoked by MUPIP RUNDOWN in which case the semaphores needs to be removed. But, remove the
				 * semaphore ONLY if we created it here OR the receive pool was successfully removed.
				 */
				remove_sem = sem_created || (SS_NORMAL == jnlpool_stat);
				if (!remove_sem)
					add_to_semids_list(repl_instance.jnlpool_semid);
				status = mu_replpool_release_sem(&repl_instance, RECVPOOL_SEGMENT, remove_sem);
				if ((SS_NORMAL == status) && remove_sem)
				{	/* Now that semaphores are removed, reset fields in file header */
					if (!sem_created)
					{	/* if sem_id was "created" by mu_replpool_grab_sem then do NOT report the
						 * MURPOOLRNDWNSUC message as it indicates that the semaphore was orphaned and we
						 * removed it when in fact there was no orphaned semaphore and we "created" it as
						 * part of mu_replpool_grab_sem to get standalone access to rundown the receiver
						 * pool (which may or may not exist)
						 */
						ipcs_ptr = i2asc((uchar_ptr_t)ipcs_buff, sem_id);
						*ipcs_ptr = '\0';
						gtm_putmsg_csa(CSA_ARG(NULL) VARLSTCNT(9) ERR_MURPOOLRNDWNSUC, 4,
								LEN_AND_STR(ipcs_buff), LEN_AND_STR(instfilename),
								ERR_SEMREMOVED, 1, sem_id);
					}
					if (NULL != jnlpool_ctl)
					{	/* Journal pool is not yet removed. So, grab lock before resetting semid/shmid
						 * fields in the file header as the function expects the caller to hold crit
						 * if the journal pool is available
						 */
						repl_csa = &FILE_INFO(jnlpool.jnlpool_dummy_reg)->s_addrs;
						assert(!repl_csa->now_crit);
						assert(!repl_csa->hold_onto_crit);
						was_crit = repl_csa->now_crit;
						/* Since we do grab_lock, below, we need to do a per-process initialization. Also,
						 * start heartbeat so that grab_lock can issue MUTEXLCKALERT and get C-stacks if
						 * waiting for crit
						 */
						START_HEARTBEAT_IF_NEEDED;
						mutex_per_process_init();
						if (!was_crit)
							grab_lock(jnlpool.jnlpool_dummy_reg, TRUE, GRAB_LOCK_ONLY);
					}
					repl_inst_recvpool_reset();
					if ((NULL != jnlpool_ctl) && !was_crit)
						rel_lock(jnlpool.jnlpool_dummy_reg);
				}
				assert(!holds_sem[RECV][RECV_POOL_ACCESS_SEM]);
			}
		} else if (rndwn_both_pools && (INVALID_SHMID != shm_id))
		{
			ipcs_ptr = i2asc((uchar_ptr_t)ipcs_buff, shm_id);
			*ipcs_ptr = '\0';
			if (rndwn_both_pools)
				gtm_putmsg_csa(CSA_ARG(NULL) VARLSTCNT(6) ERR_MURPOOLRNDWNFL, 4, LEN_AND_STR(ipcs_buff),
					LEN_AND_STR(instfilename));
		}
	}
	assert(jgbl.onlnrlbk || INST_FREEZE_ON_ERROR_POLICY || (NULL == jnlpool.repl_inst_filehdr));
	if (mur_options.rollback && (SS_NORMAL == jnlpool_stat) && (SS_NORMAL == recvpool_stat))
	{
		assert(jgbl.onlnrlbk || INST_FREEZE_ON_ERROR_POLICY || ((INVALID_SHMID == repl_instance.jnlpool_shmid)
			&& (INVALID_SHMID == repl_instance.recvpool_shmid)));
		/* Initialize jnlpool.repl_inst_filehdr as it is used later by gtmrecv_fetchresync() */
		decr_cnt = FALSE;
		if (NULL == jnlpool.repl_inst_filehdr)
		{	/* Possible if there is NO journal pool in the first place. In this case, malloc the structure here and
			 * copy the file header from repl_instance structure.
			 */
			jnlpool.repl_inst_filehdr = (repl_inst_hdr_ptr_t)malloc(SIZEOF(repl_inst_hdr));
			memcpy(jnlpool.repl_inst_filehdr, &repl_instance, SIZEOF(repl_inst_hdr));
		} else
		{
			assert(repl_instance.jnlpool_semid == jnlpool.repl_inst_filehdr->jnlpool_semid);
			assert(repl_instance.jnlpool_semid_ctime == jnlpool.repl_inst_filehdr->jnlpool_semid_ctime);
			assert(repl_instance.jnlpool_shmid == jnlpool.repl_inst_filehdr->jnlpool_shmid);
			assert(repl_instance.jnlpool_shmid_ctime == jnlpool.repl_inst_filehdr->jnlpool_shmid_ctime);
			/* If the ONLINE ROLLBACK command is run on the primary when the source server is up and running,
			 * jnlpool.repl_inst_filehdr->recvpool_semid will be INVALID because there is NO receiver server
			 * running. However, ROLLBACK creates semaphores for both journal pool and receive pool and writes
			 * it to the instance file header. Copy this information to the file header copy in the jnlpool
			 * as well
			 */
			jnlpool.repl_inst_filehdr->recvpool_semid = repl_instance.recvpool_semid;
			jnlpool.repl_inst_filehdr->recvpool_semid_ctime = repl_instance.recvpool_semid_ctime;
		}
		/* Flush changes to the replication instance file header to disk */
		repl_inst_write(instfilename, (off_t)0, (sm_uc_ptr_t)&repl_instance, SIZEOF(repl_inst_hdr));
	} else /* for MUPIP RUNDOWN, semid fields in the file header are reset and is written in mu_replpool_release_sem() above */
		decr_cnt = (NULL == jnlpool_ctl); /* for anticipatory freeze, mupip_rundown releases the semaphore */
	REVERT;
	/* Release replication instance ftok semaphore lock */
	if (!ftok_sem_release(reg, decr_cnt, immediate)) /* Do not decrement the counter if ROLLBACK */
		return FALSE;
	return ((SS_NORMAL == jnlpool_stat) && (SS_NORMAL == recvpool_stat));
}
コード例 #23
0
ファイル: jdhuff.c プロジェクト: 3bhady/CMU-PNG
jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, JHUFF_TBL * htbl,
			 d_derived_tbl ** pdtbl)
{
  d_derived_tbl *dtbl;
  int p, i, l, si;
  int lookbits, ctr;
  char huffsize[257];
  unsigned int huffcode[257];
  unsigned int code;

  /* Allocate a workspace if we haven't already done so. */
  if (*pdtbl == NULL)
    *pdtbl = (d_derived_tbl *)
      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
				  SIZEOF(d_derived_tbl));
  dtbl = *pdtbl;
  dtbl->pub = htbl;		/* fill in back link */
  
  /* Figure C.1: make table of Huffman code length for each symbol */
  /* Note that this is in code-length order. */

  p = 0;
  for (l = 1; l <= 16; l++) {
    for (i = 1; i <= (int) htbl->bits[l]; i++)
      huffsize[p++] = (char) l;
  }
  huffsize[p] = 0;
  
  /* Figure C.2: generate the codes themselves */
  /* Note that this is in code-length order. */
  
  code = 0;
  si = huffsize[0];
  p = 0;
  while (huffsize[p]) {
    while (((int) huffsize[p]) == si) {
      huffcode[p++] = code;
      code++;
    }
    code <<= 1;
    si++;
  }

  /* Figure F.15: generate decoding tables for bit-sequential decoding */

  p = 0;
  for (l = 1; l <= 16; l++) {
    if (htbl->bits[l]) {
      dtbl->valptr[l] = p; /* huffval[] index of 1st symbol of code length l */
      dtbl->mincode[l] = (long) huffcode[p]; /* minimum code of length l */
      p += htbl->bits[l];
      dtbl->maxcode[l] = (long) huffcode[p-1]; /* maximum code of length l */
    } else {
      dtbl->maxcode[l] = -1;	/* -1 if no codes of this length */
    }
  }
  dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */

  /* Compute lookahead tables to speed up decoding.
   * First we set all the table entries to 0, indicating "too long";
   * then we iterate through the Huffman codes that are short enough and
   * fill in all the entries that correspond to bit sequences starting
   * with that code.
   */

  MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));

  p = 0;
  for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
    for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
      /* l = current code's length, p = its index in huffcode[] & huffval[]. */
      /* Generate left-justified code followed by all possible bit sequences */
      lookbits = (int) (huffcode[p] << (HUFF_LOOKAHEAD-l));
      for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
	dtbl->look_nbits[lookbits] = l;
	dtbl->look_sym[lookbits] = htbl->huffval[p];
	lookbits++;
      }
    }
  }
}
コード例 #24
0
ファイル: database.cpp プロジェクト: MrtsComputers/miranda-ng
static void getDefaultProfile(TCHAR *szProfile, size_t cch, TCHAR *profiledir)
{
	TCHAR defaultProfile[MAX_PATH];
	GetPrivateProfileString(_T("Database"), _T("DefaultProfile"), _T(""), defaultProfile, SIZEOF(defaultProfile), mirandabootini);

	if (defaultProfile[0] == 0)
		return;

	VARST res(defaultProfile);
	if (res)
		mir_sntprintf(szProfile, cch, _T("%s\\%s\\%s%s"), profiledir, (TCHAR*)res, (TCHAR*)res, isValidProfileName(res) ? _T("") : _T(".dat"));
	else
		szProfile[0] = 0;
}
コード例 #25
0
ファイル: jccoefct.c プロジェクト: jrsnail/u2project_deps
compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
{
  my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  JDIMENSION blocks_across, MCUs_across, MCUindex;
  int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  JCOEF lastDC;
  jpeg_component_info *compptr;
  JBLOCKARRAY buffer;
  JBLOCKROW thisblockrow, lastblockrow;
  forward_DCT_ptr forward_DCT;

  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
       ci++, compptr++) {
    /* Align the virtual buffer for this component. */
    buffer = (*cinfo->mem->access_virt_barray)
      ((j_common_ptr) cinfo, coef->whole_image[ci],
       coef->iMCU_row_num * compptr->v_samp_factor,
       (JDIMENSION) compptr->v_samp_factor, TRUE);
    /* Count non-dummy DCT block rows in this iMCU row. */
    if (coef->iMCU_row_num < last_iMCU_row)
      block_rows = compptr->v_samp_factor;
    else {
      /* NB: can't use last_row_height here, since may not be set! */
      block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
      if (block_rows == 0) block_rows = compptr->v_samp_factor;
    }
    blocks_across = compptr->width_in_blocks;
    h_samp_factor = compptr->h_samp_factor;
    /* Count number of dummy blocks to be added at the right margin. */
    ndummy = (int) (blocks_across % h_samp_factor);
    if (ndummy > 0)
      ndummy = h_samp_factor - ndummy;
    forward_DCT = cinfo->fdct->forward_DCT[ci];
    /* Perform DCT for all non-dummy blocks in this iMCU row.  Each call
     * on forward_DCT processes a complete horizontal row of DCT blocks.
     */
    for (block_row = 0; block_row < block_rows; block_row++) {
      thisblockrow = buffer[block_row];
      (*forward_DCT) (cinfo, compptr, input_buf[ci], thisblockrow,
		      (JDIMENSION) (block_row * compptr->DCT_v_scaled_size),
		      (JDIMENSION) 0, blocks_across);
      if (ndummy > 0) {
	/* Create dummy blocks at the right edge of the image. */
	thisblockrow += blocks_across; /* => first dummy block */
	FMEMZERO((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
	lastDC = thisblockrow[-1][0];
	for (bi = 0; bi < ndummy; bi++) {
	  thisblockrow[bi][0] = lastDC;
	}
      }
    }
    /* If at end of image, create dummy block rows as needed.
     * The tricky part here is that within each MCU, we want the DC values
     * of the dummy blocks to match the last real block's DC value.
     * This squeezes a few more bytes out of the resulting file...
     */
    if (coef->iMCU_row_num == last_iMCU_row) {
      blocks_across += ndummy;	/* include lower right corner */
      MCUs_across = blocks_across / h_samp_factor;
      for (block_row = block_rows; block_row < compptr->v_samp_factor;
	   block_row++) {
	thisblockrow = buffer[block_row];
	lastblockrow = buffer[block_row-1];
	FMEMZERO((void FAR *) thisblockrow,
		 (size_t) (blocks_across * SIZEOF(JBLOCK)));
	for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
	  lastDC = lastblockrow[h_samp_factor-1][0];
	  for (bi = 0; bi < h_samp_factor; bi++) {
	    thisblockrow[bi][0] = lastDC;
	  }
	  thisblockrow += h_samp_factor; /* advance to next MCU in row */
	  lastblockrow += h_samp_factor;
	}
      }
    }
  }
  /* NB: compress_output will increment iMCU_row_num if successful.
   * A suspension return will result in redoing all the work above next time.
   */

  /* Emit data to the entropy encoder, sharing code with subsequent passes */
  return compress_output(cinfo, input_buf);
}
コード例 #26
0
ファイル: test-u32-totitle.c プロジェクト: Distrotech/gnulib
int
main ()
{
  { /* Empty string.  */
    ASSERT (check (NULL, 0, NULL, NULL, NULL, 0) == 0);
    ASSERT (check (NULL, 0, NULL, UNINORM_NFC, NULL, 0) == 0);
  }

  /* Simple string.  */
  { /* "GRÜß GOTT. ЗДРАВСТВУЙТЕ! X=(-B±SQRT(B²-4AC))/(2A)  日本語,中文,한글" */
    static const uint32_t input[] =
      { 'G', 'R', 0x00DC, 0x00DF, ' ', 'G', 'O', 'T', 'T', '.', ' ',
        0x0417, 0x0414, 0x0420, 0x0410, 0x0412, 0x0421, 0x0422, 0x0412, 0x0423,
        0x0419, 0x0422, 0x0415, '!', ' ',
        'X', '=', '(', '-', 'B', 0x00B1, 'S', 'Q', 'R', 'T', '(', 'B', 0x00B2,
        '-', '4', 'A', 'C', ')', ')', '/', '(', '2', 'A', ')', ' ', ' ',
        0x65E5, 0x672C, 0x8A9E, ',', 0x4E2D, 0x6587, ',', 0xD55C, 0xAE00, '\n'
      };
    static const uint32_t casemapped[] =
      { 'G', 'r', 0x00FC, 0x00DF, ' ', 'G', 'o', 't', 't', '.', ' ',
        0x0417, 0x0434, 0x0440, 0x0430, 0x0432, 0x0441, 0x0442, 0x0432, 0x0443,
        0x0439, 0x0442, 0x0435, '!', ' ',
        'X', '=', '(', '-', 'B', 0x00B1, 'S', 'q', 'r', 't', '(', 'B', 0x00B2,
        '-', '4', 'A', 'c', ')', ')', '/', '(', '2', 'A', ')', ' ', ' ',
        0x65E5, 0x672C, 0x8A9E, ',', 0x4E2D, 0x6587, ',', 0xD55C, 0xAE00, '\n'
      };
    ASSERT (check (input, SIZEOF (input), NULL, NULL, casemapped, SIZEOF (casemapped)) == 0);
  }

  /* Case mapping can increase the number of Unicode characters.  */
  { /* LATIN SMALL LETTER N PRECEDED BY APOSTROPHE */
    static const uint32_t input[]      = { 0x0149 };
    static const uint32_t casemapped[] = { 0x02BC, 0x004E };
    ASSERT (check (input, SIZEOF (input), NULL, NULL, casemapped, SIZEOF (casemapped)) == 0);
  }
  { /* GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS */
    static const uint32_t input[]      = { 0x0390 };
    static const uint32_t casemapped[] = { 0x0399, 0x0308, 0x0301 };
    ASSERT (check (input, SIZEOF (input), NULL, NULL, casemapped, SIZEOF (casemapped)) == 0);
  }

  /* Turkish letters i İ ı I */
  { /* LATIN CAPITAL LETTER I */
    static const uint32_t input[]      = { 0x0049 };
    static const uint32_t casemapped[] = { 0x0049 };
    ASSERT (check (input, SIZEOF (input), NULL, NULL, casemapped, SIZEOF (casemapped)) == 0);
    ASSERT (check (input, SIZEOF (input), "tr", NULL, casemapped, SIZEOF (casemapped)) == 0);
  }
  { /* LATIN SMALL LETTER I */
    static const uint32_t input[]         = { 0x0069 };
    static const uint32_t casemapped[]    = { 0x0049 };
    static const uint32_t casemapped_tr[] = { 0x0130 };
    ASSERT (check (input, SIZEOF (input), NULL, NULL, casemapped, SIZEOF (casemapped)) == 0);
    ASSERT (check (input, SIZEOF (input), "tr", NULL, casemapped_tr, SIZEOF (casemapped_tr)) == 0);
  }
  { /* LATIN CAPITAL LETTER I WITH DOT ABOVE */
    static const uint32_t input[]      = { 0x0130 };
    static const uint32_t casemapped[] = { 0x0130 };
    ASSERT (check (input, SIZEOF (input), NULL, NULL, casemapped, SIZEOF (casemapped)) == 0);
    ASSERT (check (input, SIZEOF (input), "tr", NULL, casemapped, SIZEOF (casemapped)) == 0);
  }
  { /* LATIN SMALL LETTER DOTLESS I */
    static const uint32_t input[]      = { 0x0131 };
    static const uint32_t casemapped[] = { 0x0049 };
    ASSERT (check (input, SIZEOF (input), NULL, NULL, casemapped, SIZEOF (casemapped)) == 0);
    ASSERT (check (input, SIZEOF (input), "tr", NULL, casemapped, SIZEOF (casemapped)) == 0);
  }
  { /* "topkapı" */
    static const uint32_t input[] =
      { 0x0074, 0x006F, 0x0070, 0x006B, 0x0061, 0x0070, 0x0131 };
    static const uint32_t casemapped[] =
      { 0x0054, 0x006F, 0x0070, 0x006B, 0x0061, 0x0070, 0x0131 };
    ASSERT (check (input, SIZEOF (input), NULL, NULL, casemapped, SIZEOF (casemapped)) == 0);
    ASSERT (check (input, SIZEOF (input), "tr", NULL, casemapped, SIZEOF (casemapped)) == 0);
  }

  /* Uppercasing can increase the number of Unicode characters.  */
  { /* "heiß" */
    static const uint32_t input[]      = { 0x0068, 0x0065, 0x0069, 0x00DF };
    static const uint32_t casemapped[] = { 0x0048, 0x0065, 0x0069, 0x00DF };
    ASSERT (check (input, SIZEOF (input), NULL, NULL, casemapped, SIZEOF (casemapped)) == 0);
  }

  /* Case mappings for some characters can depend on the surrounding characters.  */
  { /* "περισσότερες πληροφορίες" */
    static const uint32_t input[] =
      {
        0x03C0, 0x03B5, 0x03C1, 0x03B9, 0x03C3, 0x03C3, 0x03CC, 0x03C4,
        0x03B5, 0x03C1, 0x03B5, 0x03C2, 0x0020, 0x03C0, 0x03BB, 0x03B7,
        0x03C1, 0x03BF, 0x03C6, 0x03BF, 0x03C1, 0x03AF, 0x03B5, 0x03C2
      };
    static const uint32_t casemapped[] =
      {
        0x03A0, 0x03B5, 0x03C1, 0x03B9, 0x03C3, 0x03C3, 0x03CC, 0x03C4,
        0x03B5, 0x03C1, 0x03B5, 0x03C2, 0x0020, 0x03A0, 0x03BB, 0x03B7,
        0x03C1, 0x03BF, 0x03C6, 0x03BF, 0x03C1, 0x03AF, 0x03B5, 0x03C2
      };
    ASSERT (check (input, SIZEOF (input), NULL, NULL, casemapped, SIZEOF (casemapped)) == 0);
  }

  /* Case mapping can require subsequent normalization.  */
  { /* LATIN SMALL LETTER J WITH CARON, COMBINING DOT BELOW */
    static const uint32_t input[]                 = { 0x01F0, 0x0323 };
    static const uint32_t casemapped[]            = { 0x004A, 0x030C, 0x0323 };
    static const uint32_t casemapped_normalized[] = { 0x004A, 0x0323, 0x030C };
    ASSERT (check (input, SIZEOF (input), NULL, NULL,        casemapped, SIZEOF (casemapped)) == 0);
    ASSERT (check (input, SIZEOF (input), NULL, UNINORM_NFC, casemapped_normalized, SIZEOF (casemapped_normalized)) == 0);
  }

  return 0;
}
コード例 #27
0
ファイル: ardialog.cpp プロジェクト: 0xmono/miranda-ng
static INT_PTR CALLBACK AddReplacementDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
	switch (msg) {
	case WM_INITDIALOG:
		TranslateDialogDefault(hwndDlg);
		{
			Data *data = (Data *)lParam;
			SetWindowLongPtr(hwndDlg, GWLP_USERDATA, (LONG_PTR)data);

			SetWindowLongPtr(GetDlgItem(hwndDlg, IDC_OLD), GWLP_USERDATA, (LONG_PTR)data);
			mir_subclassWindow(GetDlgItem(hwndDlg, IDC_OLD), OnlyCharsEditProc);

			HICON hIcon = Skin_GetIcon("spellchecker_enabled");
			SendMessage(hwndDlg, WM_SETICON, ICON_BIG, (LPARAM)hIcon);
			Skin_ReleaseIcon(hIcon);

			SendDlgItemMessage(hwndDlg, IDC_OLD, EM_LIMITTEXT, 256, 0);
			SendDlgItemMessage(hwndDlg, IDC_NEW, EM_LIMITTEXT, 256, 0);

			if (!data->find.empty()) {
				scoped_free<TCHAR> tmp = data->dict->autoReplace->filterText(data->find.c_str());
				SetDlgItemText(hwndDlg, IDC_OLD, tmp);
			}
			if (!data->replace.empty())
				SetDlgItemText(hwndDlg, IDC_NEW, data->replace.c_str());

			CheckDlgButton(hwndDlg, IDC_VARIABLES, data->useVariables ? BST_CHECKED : BST_UNCHECKED);

			if (data->findReadOnly) {
				SendDlgItemMessage(hwndDlg, IDC_OLD, EM_SETREADONLY, TRUE, 0);
				EnableWindow(GetDlgItem(hwndDlg, IDC_OLD_PS), FALSE);
			}

			if (!variables_enabled) {
				ShowWindow(GetDlgItem(hwndDlg, IDC_VARIABLES), FALSE);
				ShowWindow(GetDlgItem(hwndDlg, IDC_VAR_HELP), FALSE);

				RECT rc_old;
				GetWindowRect(GetDlgItem(hwndDlg, IDC_OLD), &rc_old);
				RECT rc_new;
				GetWindowRect(GetDlgItem(hwndDlg, IDC_NEW), &rc_new);
				rc_new.right = rc_old.right;

				SetWindowPos(GetDlgItem(hwndDlg, IDC_NEW), NULL, 0, 0,
								 rc_new.right - rc_new.left, rc_new.bottom - rc_new.top,
								 SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOREDRAW | SWP_NOZORDER);
			}
			else {
				variables_skin_helpbutton(hwndDlg, IDC_VAR_HELP);
				EnableWindow(GetDlgItem(hwndDlg, IDC_VAR_HELP), IsDlgButtonChecked(hwndDlg, IDC_VARIABLES));
			}

			CenterParent(hwndDlg);
		}
		return TRUE;

	case WM_COMMAND:
		switch (wParam) {
		case IDOK:
			{
				Data *data = (Data *)GetWindowLongPtr(hwndDlg, GWLP_USERDATA);

				TCHAR find[256];
				if (data->findReadOnly)
					lstrcpyn(find, data->find.c_str(), SIZEOF(find));
				else {
					GetDlgItemText(hwndDlg, IDC_OLD, find, SIZEOF(find));
					lstrtrim(find);
				}

				TCHAR replace[256];
				GetDlgItemText(hwndDlg, IDC_NEW, replace, SIZEOF(replace));
				lstrtrim(replace);

				if (!data->findReadOnly && find[0] == 0)
					MessageBox(hwndDlg, TranslateT("The wrong word can't be empty!"), TranslateT("Wrong Correction"), MB_OK | MB_ICONERROR);

				else if (replace[0] == 0)
					MessageBox(hwndDlg, TranslateT("The correction can't be empty!"), TranslateT("Wrong Correction"), MB_OK | MB_ICONERROR);

				else if (_tcscmp(find, replace) == 0)
					MessageBox(hwndDlg, TranslateT("The correction can't be equal to the wrong word!"), TranslateT("Wrong Correction"), MB_OK | MB_ICONERROR);

				else {
					data->callback(FALSE, data->dict,
										find, replace, IsDlgButtonChecked(hwndDlg, IDC_VARIABLES),
										data->find.c_str(), data->param);
					Close(hwndDlg, 1);
				}
			}
			break;

		case IDCANCEL:
			Close(hwndDlg, 0);
			break;

		case IDC_VARIABLES:
			EnableWindow(GetDlgItem(hwndDlg, IDC_VAR_HELP), IsDlgButtonChecked(hwndDlg, IDC_VARIABLES));
			break;

		case IDC_VAR_HELP:
			variables_showhelp(hwndDlg, IDC_NEW, VHF_FULLDLG, NULL, "The wrong word typed by the user");
			break;
		}
		break;

	case WM_CLOSE:
		Close(hwndDlg, 0);
		break;
	}

	return FALSE;
}
コード例 #28
0
ファイル: mur_output_record.c プロジェクト: shabiel/fis-gtm
/* This routine is called only for recover and rollback (that is, mur_options.update).
 * It applies the set/kill/zkill, tcom, inctn, and aimg records during forward processing.
 * Some fields like jnl_seqno, rec_seqno and prefix.time are saved here from original journal files.
 * Later jnl_write routines copies them to journal records instead of generating them like the runtime system */
uint4	mur_output_record(reg_ctl_list *rctl)
{
	mval			mv;
	jnl_record		*rec;
	char			*val_ptr;
	int			strm_num;
	uint4			dummy;
	off_jnl_t		pini_addr;
	jnl_string		*keystr;
	enum jnl_record_type 	rectype;
	uint4			jnl_status, status;
	pini_list_struct	*plst;
	boolean_t		jnl_enabled, was_crit;
	struct_jrec_null	null_record;
	gd_region		*reg;
	seq_num			strm_seqno;
	sgmnt_addrs		*csa;
	sgmnt_data_ptr_t	csd;
	jnl_ctl_list		*jctl;
	jnl_format_buffer	*ztworm_jfb;
	blk_hdr_ptr_t		aimg_blk_ptr;
	int			in_len, gtmcrypt_errno;
	boolean_t		use_new_key;
	DCL_THREADGBL_ACCESS;

	SETUP_THREADGBL_ACCESS;
	assert(mur_options.update);
	rec = rctl->mur_desc->jnlrec;
	rectype = (enum jnl_record_type)rec->prefix.jrec_type;
	switch (rectype)
	{
		case JRT_ALIGN:
		case JRT_EOF:
		case JRT_EPOCH:
		case JRT_PBLK:
		case JRT_PINI:
		case JRT_TRUNC:
			return SS_NORMAL;
			break;
		default:
			break;
	}
	jgbl.gbl_jrec_time = rec->prefix.time;
	pini_addr = rec->prefix.pini_addr;
	reg = rctl->gd;
	jctl = rctl->jctl;
	assert(jctl->reg_ctl == rctl);
	assert(gv_cur_region == reg);
	csa = rctl->csa;
	assert(cs_addrs == csa);
	csd = csa->hdr;
	assert(cs_data == csd);
	jnl_enabled = JNL_ENABLED(csa);
	if (jnl_enabled)
	{
		status = mur_get_pini(jctl, pini_addr, &plst);
		if (SS_NORMAL != status)
			return status;
		prc_vec = &plst->jpv;
		csa->jnl->pini_addr = plst->new_pini_addr;
		rctl->mur_plst = plst;
	}
	if (mur_options.rollback && IS_REPLICATED(rectype))
	{
		jgbl.mur_jrec_seqno = GET_JNL_SEQNO(rec);
		if (jgbl.mur_jrec_seqno >= murgbl.consist_jnl_seqno)
		{
			assert(murgbl.losttn_seqno >= (jgbl.mur_jrec_seqno + 1));
			murgbl.consist_jnl_seqno = jgbl.mur_jrec_seqno + 1;
		}
		jgbl.mur_jrec_strm_seqno = GET_STRM_SEQNO(rec);
		strm_seqno = jgbl.mur_jrec_strm_seqno;
		if (strm_seqno)
		{	/* maintain csd->strm_reg_seqno */
			strm_num = GET_STRM_INDEX(strm_seqno);
			strm_seqno = GET_STRM_SEQ60(strm_seqno);
			assert(csd->strm_reg_seqno[strm_num] <= (strm_seqno + 1));
			csd->strm_reg_seqno[strm_num] = strm_seqno + 1;
		}
	}
	/* Assert that TREF(gd_targ_gvnh_reg) is NULL for every update that journal recovery/rollback plays forward;
	 * This is necessary to ensure every update is played in only the database file where the journal record is seen
	 * instead of across all regions that span the particular global reference. For example if ^a(1) spans db files
	 * a.dat and b.dat, and a KILL ^a(1) is done at the user level, we would see KILL ^a(1) journal records in a.mjl
	 * and b.mjl. When journal recovery processes the journal record in a.mjl, it should do the kill only in a.dat
	 * When it gets to the same journal record in b.mjl, it would do the same kill in b.dat and effectively complete
	 * the user level KILL ^a(1). If instead recovery does the KILL across all spanned regions, we would be basically
	 * doing duplicate work let alone do it out-of-order since recovery goes region by region for the most part.
	 */
	assert(NULL == TREF(gd_targ_gvnh_reg));
	if (IS_SET_KILL_ZKILL_ZTRIG(rectype))
	{	/* TP and non-TP has same format */
		keystr = (jnl_string *)&rec->jrec_set_kill.mumps_node;
		if (jnl_enabled)
		{
			MUR_SET_JNL_FENCE_CTL_TOKEN(rec->jrec_set_kill.token_seq.token, rctl);
			jnl_fence_ctl.strm_seqno = rec->jrec_set_kill.strm_seqno;
			jgbl.tp_ztp_jnl_upd_num = rec->jrec_set_kill.update_num;
			DEBUG_ONLY(jgbl.max_tp_ztp_jnl_upd_num = MAX(jgbl.max_tp_ztp_jnl_upd_num, jgbl.tp_ztp_jnl_upd_num);)
			jgbl.mur_jrec_nodeflags = keystr->nodeflags;
		}
		if (IS_FENCED(rectype))
		{	/* Even for FENCE_NONE we apply fences. Otherwise an [F/G/T/U]UPD becomes UPD etc. */
			/* op_tstart is called in "mur_forward_play_cur_jrec" already */
			if (IS_FUPD(rectype))
			{
				jnl_fence_ctl.level = 1;
				if (jnl_enabled)
				{
					jnl_fence_ctl.fence_list = JNL_FENCE_LIST_END;
					csa->next_fenced = NULL;
				}
			} else if (IS_GUPD(rectype))
			{
				jnl_fence_ctl.level = 1;
				if (jnl_enabled)
				{
					jnl_fence_ctl.fence_list = csa;
					csa->next_fenced = JNL_FENCE_LIST_END;
				}
			} else if (IS_TP(rectype))
				tp_set_sgm();
		}
#		ifdef GTM_TRIGGER
		/* Check if ^#t and if so need to increment trigger cycle in file header. Note that the below 'if' check could cause
		 * csd->db_trigger_cycle to be incremented even for the region that actually did NOT get any trigger updates. This
		 * is because some of the ^#t subscripts (like ^#t(#TNAME)) go to the DEFAULT region. So, even though a trigger was
		 * loaded only for ^a (corresponding to AREG), csd->db_trigger_cycle will be incremented for DEFAULT region as well.
		 * To avoid this, the below check should be modified to set csa->incr_db_trigger_cycle only if the ^#t subscript
		 * does not begin with '#' (similar to what is done in UPD_GV_BIND_NAME_APPROPRIATE). However, since journal
		 * recovery operates in standalone mode, the db_trigger_cycle increment to DEFAULT region should be okay since it
		 * will NOT cause any restarts
		 */
		if (IS_GVKEY_HASHT_GBLNAME(keystr->length, keystr->text))
		{
			assert(cs_addrs == csa);
			csa->incr_db_trigger_cycle = TRUE;
		}
#		endif
		if (IS_SET(rectype))
		{
			val_ptr = &keystr->text[keystr->length];
			GET_MSTR_LEN(mv.str.len, val_ptr);
			mv.str.addr = val_ptr + SIZEOF(mstr_len_t);
			mv.mvtype = MV_STR;
			op_gvput(&mv);
		} else if (IS_KILL(rectype))
		{
			if (IS_TP(rectype))
				tp_set_sgm();
			op_gvkill();
#		ifdef GTM_TRIGGER
		} else if (IS_ZTRIG(rectype))
		{
			if (IS_TP(rectype))
				tp_set_sgm();
			op_ztrigger();
#		endif
		} else
		{
			assert(IS_ZKILL(rectype));
			if (IS_TP(rectype))
				tp_set_sgm();
			op_gvzwithdraw();
		}
		if (IS_ZTP(rectype))
		{	/* Even for FENCE_NONE we apply fences. Otherwise an FUPD/GUPD becomes UPD etc. */
			assert(jnl_enabled || (JNL_FENCE_LIST_END == jnl_fence_ctl.fence_list && NULL == csa->next_fenced));
			jnl_fence_ctl.level = 0;
			if (jnl_enabled)
			{
				jnl_fence_ctl.fence_list = JNL_FENCE_LIST_END;
				csa->next_fenced = NULL;
			}
		}
		return SS_NORMAL;
	}
コード例 #29
0
ファイル: jdhuff.c プロジェクト: 3v1n0/wxWidgets
jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, wxjpeg_boolean isDC, int tblno,
			 d_derived_tbl ** pdtbl)
{
  JHUFF_TBL *htbl;
  d_derived_tbl *dtbl;
  int p, i, l, si, numsymbols;
  int lookbits, ctr;
  char huffsize[257];
  unsigned int huffcode[257];
  unsigned int code;

  /* Note that huffsize[] and huffcode[] are filled in code-length order,
   * paralleling the order of the symbols themselves in htbl->huffval[].
   */

  /* Find the input Huffman table */
  if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
    ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  htbl =
    isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  if (htbl == NULL)
    ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);

  /* Allocate a workspace if we haven't already done so. */
  if (*pdtbl == NULL)
    *pdtbl = (d_derived_tbl *)
      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
				  SIZEOF(d_derived_tbl));
  dtbl = *pdtbl;
  dtbl->pub = htbl;		/* fill in back link */
  
  /* Figure C.1: make table of Huffman code length for each symbol */

  p = 0;
  for (l = 1; l <= 16; l++) {
    i = (int) htbl->bits[l];
    if (i < 0 || p + i > 256)	/* protect against table overrun */
      ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
    while (i--)
      huffsize[p++] = (char) l;
  }
  huffsize[p] = 0;
  numsymbols = p;
  
  /* Figure C.2: generate the codes themselves */
  /* We also validate that the counts represent a legal Huffman code tree. */
  
  code = 0;
  si = huffsize[0];
  p = 0;
  while (huffsize[p]) {
    while (((int) huffsize[p]) == si) {
      huffcode[p++] = code;
      code++;
    }
    /* code is now 1 more than the last code used for codelength si; but
     * it must still fit in si bits, since no code is allowed to be all ones.
     */
    if (((JPEG_INT32) code) >= (((JPEG_INT32) 1) << si))
      ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
    code <<= 1;
    si++;
  }

  /* Figure F.15: generate decoding tables for bit-sequential decoding */

  p = 0;
  for (l = 1; l <= 16; l++) {
    if (htbl->bits[l]) {
      /* valoffset[l] = huffval[] index of 1st symbol of code length l,
       * minus the minimum code of length l
       */
      dtbl->valoffset[l] = (JPEG_INT32) p - (JPEG_INT32) huffcode[p];
      p += htbl->bits[l];
      dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
    } else {
      dtbl->maxcode[l] = -1;	/* -1 if no codes of this length */
    }
  }
  dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */

  /* Compute lookahead tables to speed up decoding.
   * First we set all the table entries to 0, indicating "too long";
   * then we iterate through the Huffman codes that are short enough and
   * fill in all the entries that correspond to bit sequences starting
   * with that code.
   */

  MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));

  p = 0;
  for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
    for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
      /* l = current code's length, p = its index in huffcode[] & huffval[]. */
      /* Generate left-justified code followed by all possible bit sequences */
      lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
      for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
	dtbl->look_nbits[lookbits] = l;
	dtbl->look_sym[lookbits] = htbl->huffval[p];
	lookbits++;
      }
    }
  }

  /* Validate symbols as being reasonable.
   * For AC tables, we make no check, but accept all byte values 0..255.
   * For DC tables, we require the symbols to be in range 0..15.
   * (Tighter bounds could be applied depending on the data depth and mode,
   * but this is sufficient to ensure safe decoding.)
   */
  if (isDC) {
    for (i = 0; i < numsymbols; i++) {
      int sym = htbl->huffval[i];
      if (sym < 0 || sym > 15)
	ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
    }
  }
}
コード例 #30
0
int rc_prc_lock(rc_q_hdr *qhdr)
{
	rc_req_lock	*req;
	rc_sbkey	*sbk;
	short		i, len, pid_len;
	mval		lock, ext;
	mlk_pvtblk	**prior, *mp, *x;
	rc_lknam	*fl;
	unsigned char	action;
	bool		blocked;
	char		key_buff[KEY_BUFF_SIZE], *lkname;
	unsigned char	buff[12], *cp;
	short		subcnt;
	int		in_pid, locks_done, temp;

	ESTABLISH_RET(rc_dbms_ch, RC_SUCCESS);
	/*  Clean up dead locks in private list */
	for (prior = &mlk_pvt_root; *prior; )
	{	if (!(*prior)->granted || !(*prior)->nodptr || (*prior)->nodptr->owner != omi_pid)
			mlk_pvtblk_delete(prior);
		else
		{	(*prior)->trans = 0;
			prior = &(*prior)->next;
		}
	}

	req = (rc_req_lock *)qhdr;
	in_pid = ((qhdr->r.pid1.value << 16) | qhdr->r.pid2.value);
	cp = i2asc(buff,in_pid);
	pid_len = cp - buff;
	lks_this_cmd = 0;
	if (req->hdr.r.fmd.value & RC_MODE_CLEARLOCK)
	{	/*  Loop through all the locks, unlocking ones that belong to this client */
		for (prior = &mlk_pvt_root; *prior; )
		{	if ((*prior)->nodptr->auxowner == rc_auxown
					&& pid_len == (*prior)->value[(*prior)->total_length]
					&& !memcmp(&(*prior)->value[(*prior)->total_length+1],
					buff,pid_len))
 			{	mlk_unlock(*prior);
				mlk_pvtblk_delete(prior);
			}else
				prior = &(*prior)->next;
		}
		action = LOCKED;
	} else if (req->hdr.r.fmd.value & RC_MODE_DECRLOCK)
	{	sbk = &req->dlocks[0].sb_key;
		fl = req->dlocks;

		/*  Loop through all requested locks */
		for ( i = 0; i < req->nlocks.value; i++)
		{
			if ((char *) fl - (char *) req + sbk->len.value + 1 > req->hdr.r.len.value)
			{	/* we are beyond the end of this packet and still have
				 * lock requests to process.  Bad packet.
				 */
				qhdr->a.erc.value = RC_BADXBUF;
				REVERT;
#ifdef DEBUG
				gtcm_cpktdmp((char *)qhdr,qhdr->a.len.value,"Bad Rq: Invalid nLockNames value.");
#endif
				return -1;
			}

			if ((temp = rc_frmt_lck(key_buff, KEY_BUFF_SIZE, (unsigned char *)sbk->key, sbk->len.value, &subcnt)) < 0)
			{
			        temp = -temp;
			        qhdr->a.erc.value = temp;
				REVERT;

#ifdef DEBUG
				if (temp == RC_KEYTOOLONG)
				       gtcm_cpktdmp((char *)qhdr,qhdr->a.len.value,"RC_KEYTOOLONG.");
				else
				       gtcm_cpktdmp((char *)qhdr,qhdr->a.len.value,"Invalid lock request.");
#endif
				return -1;
			}
			temp += subcnt;

			/*  Loop through all owned locks looking for requested one */
			for (prior = &mlk_pvt_root; *prior; )
			{	if ((*prior)->nodptr->auxowner == rc_auxown
						&& temp == (*prior)->total_length
						&& !memcmp(&(*prior)->value[0],key_buff,temp)
						&& pid_len == (*prior)->value[(*prior)->total_length]
						&& !memcmp(&(*prior)->value[(*prior)->total_length+1],
						buff,pid_len))
	 			{	(*prior)->level -= 1;
					if (!(*prior)->level)
					{	mlk_unlock(*prior);
						mlk_pvtblk_delete(prior);
					}
				}else
					prior = &(*prior)->next;
			}
		fl = (rc_lknam*)((char *)fl + sbk->len.value - 1 + SIZEOF(rc_lknam));
		sbk = &fl->sb_key;

		}
		qhdr->a.erc.value = RC_SUCCESS;
		REVERT;
		return 0;
	} else
		action = INCREMENTAL;
	lock.mvtype = ext.mvtype = MV_STR;
	lkname = (char*)req->dlocks[0].sb_key.key;
	sbk = &req->dlocks[0].sb_key;
	fl = req->dlocks;
	for ( i = 0; i < req->nlocks.value; i++)
	{
		if ((char *) fl - (char *) req + sbk->len.value + 1 > req->hdr.r.len.value)
		{	/* we are beyond the end of this packet and still have
			 * lock requests to process.  Bad packet.
			 */
			qhdr->a.erc.value = RC_BADXBUF;
			REVERT;
#ifdef DEBUG
			gtcm_cpktdmp((char *)qhdr,qhdr->a.len.value,"Bad Rq: Invalid nLockNames value.");
#endif
			return -1;
		}

		if ((qhdr->a.erc.value = rc_fnd_file(&fl->xdsid)) != RC_SUCCESS)
		    {
			REVERT;
#ifdef DEBUG
	gtcm_cpktdmp((char *)qhdr,qhdr->a.len.value,"rc_fnd_file failed.");
#endif
			return -1;
		    }

		if ((temp = rc_frmt_lck(key_buff, KEY_BUFF_SIZE, (unsigned char *)sbk->key, sbk->len.value, &subcnt)) < 0)
		{
			temp = -temp;
			qhdr->a.erc.value = temp;
			REVERT;
#ifdef DEBUG
			if (temp == RC_KEYTOOLONG)
				gtcm_cpktdmp((char *)qhdr,qhdr->a.len.value,"RC_KEYTOOLONG.");
			else
				gtcm_cpktdmp((char *)qhdr,qhdr->a.len.value,"Invalid lock request.");
#endif
			return -1;
		}
		temp += subcnt;
		mp = (mlk_pvtblk*)malloc(SIZEOF(mlk_pvtblk) + temp + pid_len + 1);
		memset(mp, 0, SIZEOF(mlk_pvtblk) - 1);
		mp->subscript_cnt = subcnt;
		mp->total_length = temp;
		memcpy(mp->value, key_buff, mp->total_length);
		mp->region = gv_cur_region;
		mp->ctlptr = (mlk_ctldata*)cs_addrs->lock_addrs[0];
		mp->value[mp->total_length] = pid_len;
		memcpy(&mp->value[mp->total_length + 1], buff, pid_len);
		if (!mlk_pvtblk_insert(mp))
		{	if (!(mp->value[mp->total_length] == mlk_pvt_root->value[mlk_pvt_root->total_length]
				&& !memcmp(&mp->value[mp->total_length + 1], &mlk_pvt_root->value[mp->total_length + 1],
				mp->total_length + 1)))
			{	free(mp);	/* Server owns lock on behalf of a different agent/client pair */
				REVERT;
				qhdr->a.erc.value = RC_LOCKCONFLICT;
				return 0;	/* Return lock not granted */
			}
			free(mp);
		} else if (mp != mlk_pvt_root)
		{	REVERT;
			qhdr->a.erc.value = RC_GLOBERRUNSPEC;
#ifdef DEBUG
	gtcm_cpktdmp((char *)qhdr,qhdr->a.len.value,"RC_GLOBERRUNSPEC.");
#endif
			return -1;/* error */

		}
		fl = (rc_lknam*)((char *)fl + sbk->len.value - 1 + SIZEOF(rc_lknam));
		sbk = &fl->sb_key;
	}
	blocked = FALSE;
	lckclr();
	for (x = mlk_pvt_root, locks_done = 0; locks_done < lks_this_cmd; x = x->next)
	{
	        locks_done++;
		/* If lock is obtained */
		if (!mlk_lock(x,rc_auxown,TRUE))
		{
			x->granted = TRUE;
			if (action == INCREMENTAL)
				x->level += x->translev;
			else
				x->level = 1;
		} else
		{
			blocked = TRUE;
			break;
		}
	}
	if (blocked)	/* need to back out all locks */
	{
		for (x = mlk_pvt_root, i = 0;
			i < locks_done ; x = x->next, i++)
		{
			mlk_bckout(x, action);
		}
		qhdr->a.erc.value = RC_LOCKCONFLICT;
	} else
		qhdr->a.erc.value = RC_SUCCESS;
	REVERT;
	return 0;
}