/* * NAME: hfs->format() * DESCRIPTION: write a new filesystem */ int hfs_format(const char *path, int pnum, int mode, const char *vname, unsigned int nbadblocks, const unsigned long badblocks[]) { hfsvol vol; btree *ext = &vol.ext; btree *cat = &vol.cat; unsigned int i, *badalloc = 0; v_init(&vol, mode); if (! validvname(vname)) goto fail; if (v_open(&vol, path, HFS_MODE_RDWR) == -1 || v_geometry(&vol, pnum) == -1) goto fail; /* initialize volume geometry */ vol.lpa = 1 + ((vol.vlen - 6) >> 16); if (vol.flags & HFS_OPT_2048) vol.lpa = (vol.lpa + 3) & ~3; vol.vbmsz = (vol.vlen / vol.lpa + 0x0fff) >> 12; vol.mdb.drSigWord = HFS_SIGWORD; vol.mdb.drCrDate = d_mtime(time(0)); vol.mdb.drLsMod = vol.mdb.drCrDate; vol.mdb.drAtrb = 0; vol.mdb.drNmFls = 0; vol.mdb.drVBMSt = 3; vol.mdb.drAllocPtr = 0; vol.mdb.drAlBlkSiz = vol.lpa << HFS_BLOCKSZ_BITS; vol.mdb.drClpSiz = vol.mdb.drAlBlkSiz << 2; vol.mdb.drAlBlSt = vol.mdb.drVBMSt + vol.vbmsz; if (vol.flags & HFS_OPT_2048) vol.mdb.drAlBlSt = ((vol.vstart & 3) + vol.mdb.drAlBlSt + 3) & ~3; vol.mdb.drNmAlBlks = (vol.vlen - 2 - vol.mdb.drAlBlSt) / vol.lpa; vol.mdb.drNxtCNID = HFS_CNID_ROOTDIR; /* modified later */ vol.mdb.drFreeBks = vol.mdb.drNmAlBlks; strcpy(vol.mdb.drVN, vname); vol.mdb.drVolBkUp = 0; vol.mdb.drVSeqNum = 0; vol.mdb.drWrCnt = 0; vol.mdb.drXTClpSiz = vol.mdb.drNmAlBlks / 128 * vol.mdb.drAlBlkSiz; vol.mdb.drCTClpSiz = vol.mdb.drXTClpSiz; vol.mdb.drNmRtDirs = 0; vol.mdb.drFilCnt = 0; vol.mdb.drDirCnt = -1; /* incremented when root directory is created */ for (i = 0; i < 8; ++i) vol.mdb.drFndrInfo[i] = 0; vol.mdb.drEmbedSigWord = 0x0000; vol.mdb.drEmbedExtent.xdrStABN = 0; vol.mdb.drEmbedExtent.xdrNumABlks = 0; /* vol.mdb.drXTFlSize */ /* vol.mdb.drCTFlSize */ /* vol.mdb.drXTExtRec[0..2] */ /* vol.mdb.drCTExtRec[0..2] */ vol.flags |= HFS_VOL_UPDATE_MDB | HFS_VOL_UPDATE_ALTMDB; /* initialize volume bitmap */ vol.vbm = ALLOC(block, vol.vbmsz); if (vol.vbm == 0) ERROR(ENOMEM, 0); memset(vol.vbm, 0, vol.vbmsz << HFS_BLOCKSZ_BITS); vol.flags |= HFS_VOL_UPDATE_VBM; /* perform initial bad block sparing */ if (nbadblocks > 0) { if (nbadblocks * 4 > vol.vlen) ERROR(EINVAL, "volume contains too many bad blocks"); badalloc = ALLOC(unsigned int, nbadblocks); if (badalloc == 0) ERROR(ENOMEM, 0); if (vol.mdb.drNmAlBlks == 1594) vol.mdb.drFreeBks = --vol.mdb.drNmAlBlks; for (i = 0; i < nbadblocks; ++i) { unsigned long bnum; unsigned int anum; bnum = badblocks[i]; if (bnum < vol.mdb.drAlBlSt || bnum == vol.vlen - 2) ERROR(EINVAL, "can't spare critical bad block"); else if (bnum >= vol.vlen) ERROR(EINVAL, "bad block not in volume"); anum = (bnum - vol.mdb.drAlBlSt) / vol.lpa; if (anum < vol.mdb.drNmAlBlks) BMSET(vol.vbm, anum); badalloc[i] = anum; } vol.mdb.drAtrb |= HFS_ATRB_BBSPARED; } /* create extents overflow file */ n_init(&ext->hdrnd, ext, ndHdrNode, 0); ext->hdrnd.nnum = 0; ext->hdrnd.nd.ndNRecs = 3; ext->hdrnd.roff[1] = 0x078; ext->hdrnd.roff[2] = 0x0f8; ext->hdrnd.roff[3] = 0x1f8; memset(HFS_NODEREC(ext->hdrnd, 1), 0, 128); ext->hdr.bthDepth = 0; ext->hdr.bthRoot = 0; ext->hdr.bthNRecs = 0; ext->hdr.bthFNode = 0; ext->hdr.bthLNode = 0; ext->hdr.bthNodeSize = HFS_BLOCKSZ; ext->hdr.bthKeyLen = 0x07; ext->hdr.bthNNodes = 0; ext->hdr.bthFree = 0; for (i = 0; i < 76; ++i) ext->hdr.bthResv[i] = 0; ext->map = ALLOC(byte, HFS_MAP1SZ); if (ext->map == 0) ERROR(ENOMEM, 0); memset(ext->map, 0, HFS_MAP1SZ); BMSET(ext->map, 0); ext->mapsz = HFS_MAP1SZ; ext->flags = HFS_BT_UPDATE_HDR; /* create catalog file */ n_init(&cat->hdrnd, cat, ndHdrNode, 0); cat->hdrnd.nnum = 0; cat->hdrnd.nd.ndNRecs = 3; cat->hdrnd.roff[1] = 0x078; cat->hdrnd.roff[2] = 0x0f8; cat->hdrnd.roff[3] = 0x1f8; memset(HFS_NODEREC(cat->hdrnd, 1), 0, 128); cat->hdr.bthDepth = 0; cat->hdr.bthRoot = 0; cat->hdr.bthNRecs = 0; cat->hdr.bthFNode = 0; cat->hdr.bthLNode = 0; cat->hdr.bthNodeSize = HFS_BLOCKSZ; cat->hdr.bthKeyLen = 0x25; cat->hdr.bthNNodes = 0; cat->hdr.bthFree = 0; for (i = 0; i < 76; ++i) cat->hdr.bthResv[i] = 0; cat->map = ALLOC(byte, HFS_MAP1SZ); if (cat->map == 0) ERROR(ENOMEM, 0); memset(cat->map, 0, HFS_MAP1SZ); BMSET(cat->map, 0); cat->mapsz = HFS_MAP1SZ; cat->flags = HFS_BT_UPDATE_HDR; /* allocate space for header nodes (and initial extents) */ if (bt_space(ext, 1) == -1 || bt_space(cat, 1) == -1) goto fail; --ext->hdr.bthFree; --cat->hdr.bthFree; /* create extent records for bad blocks */ if (nbadblocks > 0) { hfsfile bbfile; ExtDescriptor extent; ExtDataRec *extrec; ExtKeyRec key; byte record[HFS_MAX_EXTRECLEN]; unsigned int reclen; f_init(&bbfile, &vol, HFS_CNID_BADALLOC, "bad blocks"); qsort(badalloc, nbadblocks, sizeof(*badalloc), (int (*)(const void *, const void *)) compare); for (i = 0; i < nbadblocks; ++i) { if (i == 0 || badalloc[i] != extent.xdrStABN) { extent.xdrStABN = badalloc[i]; extent.xdrNumABlks = 1; if (extent.xdrStABN < vol.mdb.drNmAlBlks && f_addextent(&bbfile, &extent) == -1) goto fail; } } /* flush local extents into extents overflow file */ f_getptrs(&bbfile, &extrec, 0, 0); r_makeextkey(&key, bbfile.fork, bbfile.cat.u.fil.filFlNum, 0); r_packextrec(&key, extrec, record, &reclen); if (bt_insert(&vol.ext, record, reclen) == -1) goto fail; } vol.flags |= HFS_VOL_MOUNTED; /* create root directory */ if (v_mkdir(&vol, HFS_CNID_ROOTPAR, vname) == -1) goto fail; vol.mdb.drNxtCNID = 16; /* first CNID not reserved by Apple */ /* write boot blocks */ if (m_zerobb(&vol) == -1) goto fail; /* zero other unused space, if requested */ if (vol.flags & HFS_OPT_ZERO) { block b; unsigned long bnum; memset(&b, 0, sizeof(b)); /* between MDB and VBM (never) */ for (bnum = 3; bnum < vol.mdb.drVBMSt; ++bnum) b_writelb(&vol, bnum, &b); /* between VBM and first allocation block (sometimes if HFS_OPT_2048) */ for (bnum = vol.mdb.drVBMSt + vol.vbmsz; bnum < vol.mdb.drAlBlSt; ++bnum) b_writelb(&vol, bnum, &b); /* between last allocation block and alternate MDB (sometimes) */ for (bnum = vol.mdb.drAlBlSt + vol.mdb.drNmAlBlks * vol.lpa; bnum < vol.vlen - 2; ++bnum) b_writelb(&vol, bnum, &b); /* final block (always) */ b_writelb(&vol, vol.vlen - 1, &b); } /* write boot blocks */ b_writelb(&vol, 0, (block*)bootblocks); b_writelb(&vol, 1, (block*)&bootblocks[HFS_BLOCKSZ]); /* flush remaining state and close volume */ if (v_close(&vol) == -1) goto fail; FREE(badalloc); return 0; fail: v_close(&vol); FREE(badalloc); return -1; }
void drawallbuttons(struct w_window *w) { static struct w_b_choose modebutton, modifybutton, pigfile; static struct w_b_press movebutton[6], pogfile; struct w_button *b1, *b2, *b3; struct ws_bitmap *bm; int i, j, k, bxsize, bysize, y; char **pignames; modifybutton.num_options = tt_number; modifybutton.options = (const char **)init.bnames; modifybutton.selected = view.currmode; modifybutton.select_lroutine = modifybutton.select_rroutine = b_changemode; modebutton.num_options = mt_number; modebutton.options = movemodes; modebutton.selected = view.movemode; modebutton.select_lroutine = modebutton.select_rroutine = b_changemovemode; if (init.d_ver >= d2_10_reg) { pignames = ws_getallfilenames(init.pigpaths[init.d_ver], "pig", &pigfile.num_options); checkmem( pigfile.options = MALLOC(sizeof(char *) * pigfile.num_options) ); pigfile.selected = 0; for (i = 0; i < pigfile.num_options; i++) { pignames[i][strlen(pignames[i]) - 4] = 0; checkmem( pigfile.options[i] = MALLOC(strlen(pignames[i]) + 1) ); strcpy( (char *)pigfile.options[i], pignames[i] ); for (j = 1; j < strlen(pigfile.options[i]); j++) { *( (char *)pigfile.options[i] + j ) = tolower( pigfile.options[i][j]); } strcat(pignames[i], ".256"); if ( l && !strcmp(pignames[i], l->pigname) ) { pigfile.selected = i; } FREE(pignames[i]); } FREE(pignames); pigfile.select_lroutine = pigfile.select_rroutine = b_changepigfile; } checkmem( view.b_levels = MALLOC( sizeof(struct w_b_choose) ) ); view.b_levels->num_options = 1; checkmem( view.b_levels->options = MALLOC(sizeof(char *) * 1) ); view.b_levels->options[0] = TXT_NONE; view.b_levels->selected = 0; view.b_levels->select_lroutine = view.b_levels->select_rroutine = b_changelevel; bxsize = w_xwininsize(w) / 3; w_refreshstart(w); checkmem( b1 = b_currmode = w_addstdbutton(w, w_b_choose, 0, y = 0, bxsize * 3, -1, TXT_MODIFYWHAT, &modifybutton, 1) ); y += b1->ysize; checkmem( b2 = b_movemode = w_addstdbutton(w, w_b_choose, 0, y, bxsize * 3, -1, TXT_MOVEMODE, &modebutton, 1) ); y += b2->ysize; checkmem( view.levelbutton = w_addstdbutton(w, w_b_choose, 0, y, bxsize * 3, -1, TXT_LEVEL, view.b_levels, 1) ); y += view.levelbutton->ysize; if (init.d_ver >= d2_10_reg) { checkmem( b3 = b_pigfile = w_addstdbutton(w, w_b_choose, 0, y, bxsize * 3, -1, TXT_LEVELPIGFILE, &pigfile, 1) ); y += b3->ysize; if (init.d_ver >= d2_12_reg) { pogfile.delay = 0; pogfile.repeat = -1; pogfile.l_pressed_routine = pogfile.r_pressed_routine = NULL; pogfile.l_routine = pogfile.r_routine = b_changepogfile; checkmem( b_pogfile = w_addstdbutton(w, w_b_press, 0, y, bxsize * 3, -1, TXT_POGFILE, &pogfile, 1) ); y += b_pogfile->ysize; } } bysize = (w_ywininsize(w) - y) / 2; /* move button menu */ for (j = 5; j < 22; j++) { for (k = 1; k < 5; k += 2) { mbls[2][j * 5 + k] = -mbls[0][j * 5 + k]; mbls[2][j * 5 + k + 1] = mbls[0][j * 5 + k + 1]; mbls[4][j * 5 + k] = mbls[1][j * 5 + k]; mbls[4][j * 5 + k + 1] = mbls[1][j * 5 + k + 1]; mbls[3][j * 5 + k] = -mbls[1][j * 5 + k + 1]; mbls[3][j * 5 + k + 1] = -mbls[1][j * 5 + k]; mbls[5][j * 5 + k] = -mbls[3][j * 5 + k]; mbls[5][j * 5 + k + 1] = mbls[3][j * 5 + k + 1]; mbls[1][j * 5 + k + 1] = -mbls[1][j * 5 + k + 1]; } } for (i = 0; i < 6; i++) { for (j = 0; j < 22; j++) { mbls[i][j * 5] = view.color[WHITE]; /* I was too lazy to do this by hand: */ for (k = 1; k < 5; k += 2) { mbls[i][j * 5 + k] += j < 5 ? 35 : i == 1 || i == 4 ? 4 : 11; mbls[i][j * 5 + k + 1] += j >= 5 && (i == 3 || i == 5) ? 18 : 11; } } } for (j = 0; j < 2; j++) { for (i = 0; i < 3; i++) { checkmem( bm = w_createlinesbm(bxsize - 2, bysize - 2, j * 3 + i == 0 || j * 3 + i == 2 ? 22 : 14, mbls[j * 3 + i]) ); movebuttondata[j * 3 + i] = ws_getbitmapdata(bm); movebuttondsize[j * 3 + i] = bm->xsize * bm->ysize; movebutton[j * 3 + i].l_routine = movebutton[j * 3 + i].l_pressed_routine = b_turnall[j * 3 + i]; movebutton[j * 3 + i].r_routine = movebutton[j * 3 + i].r_pressed_routine = b_moveall[j * 3 + i]; movebutton[j * 3 + i].delay = 25; movebutton[j * 3 + i].repeat = 5; checkmem( b_movebts[j * 3 + i] = w_addimagebutton(w, w_b_press, i * bxsize, j * bysize + y, -1, -1, bm, bm, &movebutton[j * 3 + i], 0, 1) ); } } w_refreshend(w); }
static INLINE void disposeFpgmPrep(MOVE table_fpgm_prep *table) { if (table->tag) sdsfree(table->tag); if (table->bytes) FREE(table->bytes); }
CvMat * mvg_triangulation_RANSAC( const CvMat * projection_matrices[], const CvMat * projected_points, const bool affine, const bool normalize_A /*= false*/, const int min_inliers_to_triangulate /*= MVG_MIN_INLIERS_TO_TRIANGULATE*/, const int min_inliers_to_triangulate_weaker /*= MVG_MIN_INLIERS_TO_TRIANGULATE_WEAKER*/, const int trials /*= MVG_RANSAC_TRIANGULATION_TRIALS*/, const double threshold /*= MVG_MEASUREMENT_THRESHOLD*/, bool * inliers /*= NULL*/ ) { // printf("Triangulating: "); // transform input const int n = projected_points->cols; const double threshold_sq = threshold * threshold; // fail immediately if the solution is underdetermined if (n < 2) { return false; } // allocate bool * best_status = ALLOC(bool, n), * status = ALLOC(bool, n); int best_inliers_count = -1; // do this many times for (int i = 0; i < trials; i++) { // pick randomly 2 points memset(status, 0, sizeof(bool) * n); int samples[2]; for (int count = 0; count < 2;) { const int pick = rand() % n; if (!status[pick]) { status[pick] = true; samples[count] = pick; count++; } } // calculate using mvg_triangulation_SVD_affine CvMat * X = affine ? mvg_triangulation_SVD_affine(projection_matrices, projected_points, normalize_A, 2, samples, 2) : mvg_triangulation_SVD(projection_matrices, projected_points, normalize_A, 2, samples, 2); if (!X) { continue; } // count and mark the inliers int inliers_count = 0; for (int j = 0; j < n; j++) { double reprojection[2]; // note that here we're using "dirty" projection method which is suitable only for visualization; on the upside, it shouldn't matter because // if a point is projected on pi_infinity, there's something wrong with it anyway if (affine) { opencv_vertex_projection_visualization(projection_matrices[j], OPENCV_ELEM(X, 0, 0), OPENCV_ELEM(X, 1, 0), OPENCV_ELEM(X, 2, 0), reprojection); } else { opencv_vertex_projection_visualization(projection_matrices[j], OPENCV_ELEM(X, 0, 0), OPENCV_ELEM(X, 1, 0), OPENCV_ELEM(X, 2, 0), OPENCV_ELEM(X, 3, 0), reprojection); } const double dx = reprojection[0] - OPENCV_ELEM(projected_points, 0, j), dy = reprojection[1] - OPENCV_ELEM(projected_points, 1, j); if (dx * dx + dy * dy <= threshold_sq) { inliers_count++; status[j] = true; } else { status[j] = false; } } cvReleaseMat(&X); // check for the best sample if (inliers_count > best_inliers_count) { bool * temp = best_status; best_status = status; status = temp; best_inliers_count = inliers_count; } // debug // printf("{%d/%d} ", inliers_count, n); } FREE(status); if (best_inliers_count < 2) { FREE(best_status); return false; } // calculate camera calibration using only inliers int * samples = ALLOC(int, best_inliers_count); int j = 0; int outliers = 0, min = min_inliers_to_triangulate; for (int i = 0; i < n; i++) { if (best_status[i]) { samples[j++] = i; } else { outliers++; } } if (outliers == 0) min = min_inliers_to_triangulate_weaker; CvMat * X = affine ? mvg_triangulation_SVD_affine(projection_matrices, projected_points, true, min, samples, best_inliers_count) : mvg_triangulation_SVD(projection_matrices, projected_points, true, min, samples, best_inliers_count); if (!X) { // printf("failed to estimate\n"); if (inliers) { memset(inliers, 0, sizeof(bool) * n); } } else if (inliers) { memcpy(inliers, best_status, sizeof(bool) * n); } // release resources FREE(samples); FREE(best_status); // printf("\n"); return X; }
static krb5_error_code krb5_rc_dfl_recover_locked(krb5_context context, krb5_rcache id) { #ifdef NOIOSTUFF return KRB5_RC_NOIO; #else struct dfl_data *t = (struct dfl_data *)id->data; krb5_donot_replay *rep = 0; krb5_error_code retval; long max_size; int expired_entries = 0; krb5_int32 now; if ((retval = krb5_rc_io_open(context, &t->d, t->name))) { return retval; } t->recovering = 1; max_size = krb5_rc_io_size(context, &t->d); rep = NULL; if (krb5_rc_io_read(context, &t->d, (krb5_pointer) &t->lifespan, sizeof(t->lifespan))) { retval = KRB5_RC_IO; goto io_fail; } if (!(rep = (krb5_donot_replay *) malloc(sizeof(krb5_donot_replay)))) { retval = KRB5_RC_MALLOC; goto io_fail; } rep->client = NULL; rep->server = NULL; if (krb5_timeofday(context, &now)) now = 0; /* now read in each auth_replay and insert into table */ for (;;) { if (krb5_rc_io_mark(context, &t->d)) { retval = KRB5_RC_IO; goto io_fail; } retval = krb5_rc_io_fetch(context, t, rep, (int) max_size); if (retval == KRB5_RC_IO_EOF) break; else if (retval != 0) goto io_fail; if (alive(now, rep, t->lifespan) != CMP_EXPIRED) { if (rc_store(context, id, rep, now) == CMP_MALLOC) { retval = KRB5_RC_MALLOC; goto io_fail; } } else { expired_entries++; } /* * free fields allocated by rc_io_fetch */ FREE(rep->server); FREE(rep->client); rep->server = 0; rep->client = 0; } retval = 0; krb5_rc_io_unmark(context, &t->d); /* * An automatic expunge here could remove the need for * mark/unmark but that would be inefficient. */ io_fail: krb5_rc_free_entry(context, &rep); if (retval) krb5_rc_io_close(context, &t->d); else if (expired_entries > EXCESSREPS) retval = krb5_rc_dfl_expunge_locked(context, id); t->recovering = 0; return retval; #endif }
void val_log_assertion_pfx(const val_context_t * ctx, int level, const char *prefix, const char * name_pr, struct val_authentication_chain *next_as) { char name_buf[INET6_ADDRSTRLEN + 1]; const char *serv_pr; int tag = 0; int class_h; int type_h; struct val_rr_rec *data; struct val_rr_rec *sig; struct sockaddr *serv; val_astatus_t status; struct val_rr_rec *curkey, *cursig; if (next_as == NULL) return; class_h = next_as->val_ac_rrset->val_rrset_class; type_h = next_as->val_ac_rrset->val_rrset_type; data = next_as->val_ac_rrset->val_rrset_data; sig = next_as->val_ac_rrset->val_rrset_sig; serv = next_as->val_ac_rrset->val_rrset_server; status = next_as->val_ac_status; if (NULL == prefix) prefix = ""; if (serv) serv_pr = ((serv_pr = val_get_ns_string(serv, name_buf, sizeof(name_buf))) == NULL) ? "VAL_CACHE" : serv_pr; else serv_pr = "NULL"; if (type_h == ns_t_dnskey) { for (curkey = data; curkey; curkey = curkey->rr_next) { if ((curkey->rr_status == VAL_AC_VERIFIED_LINK) || (curkey->rr_status == VAL_AC_TRUST_POINT) || (curkey->rr_status == VAL_AC_UNKNOWN_ALGORITHM_LINK)) { /* * Extract the key tag */ val_dnskey_rdata_t dnskey; if (VAL_NO_ERROR != val_parse_dnskey_rdata(curkey->rr_rdata, curkey->rr_rdata_length, &dnskey)) { val_log(ctx, LOG_INFO, "val_log_assertion_pfx(): Cannot parse DNSKEY data"); } else { tag = dnskey.key_tag; if (dnskey.public_key) FREE(dnskey.public_key); } break; } } } if (tag != 0) { val_log(ctx, level, "%sname=%s class=%s type=%s[tag=%d] from-server=%s " "status=%s:%d", prefix, name_pr, p_class(class_h), p_type(type_h), tag, serv_pr, p_ac_status(status), status); } else { val_log(ctx, level, "%sname=%s class=%s type=%s from-server=%s status=%s:%d", prefix, name_pr, p_class(class_h), p_type(type_h), serv_pr, p_ac_status(status), status); } #if 0 for (cursig = sig; cursig; cursig = cursig->rr_next) { char incpTime[1028]; char exprTime[1028]; struct timeval tv_sig; val_rrsig_rdata_t rrsig; val_parse_rrsig_rdata(cursig->rr_rdata, cursig->rr_rdata_length, &rrsig); memset(&tv_sig, 0, sizeof(tv_sig)); tv_sig.tv_sec = rrsig.sig_incp; GET_TIME_BUF((const time_t *)(&tv_sig.tv_sec), incpTime); memset(&tv_sig, 0, sizeof(tv_sig)); tv_sig.tv_sec = rrsig.sig_expr; GET_TIME_BUF((const time_t *)(&tv_sig.tv_sec), exprTime); val_log(ctx, level, "%s ->tag=%d status=%s sig-incep=%s sig-expr=%s", prefix, rrsig.key_tag, p_ac_status(cursig->rr_status), incpTime, exprTime); } #endif #if 0 struct val_rr_rec *rr; struct val_rr_rec *sig = next_as->val_ac_rrset->val_rrset_sig; for (rr = data; rr; rr = rr->rr_next) { val_log(ctx, level, " data_status=%s:%d", p_ac_status(rr->rr_status), rr->rr_status); } for (rr = sig; rr; rr = rr->rr_next) { val_log(ctx, level, " sig_status=%s:%d", p_ac_status(rr->rr_status), rr->rr_status); } #endif }
/* * Creates the config file and tells i3 to reload. * */ static void finish() { printf("creating \"%s\"...\n", config_path); if (!(dpy = XOpenDisplay(NULL))) errx(1, "Could not connect to X11"); FILE *kc_config = fopen(SYSCONFDIR "/i3/config.keycodes", "r"); if (kc_config == NULL) err(1, "Could not open input file \"%s\"", SYSCONFDIR "/i3/config.keycodes"); FILE *ks_config = fopen(config_path, "w"); if (ks_config == NULL) err(1, "Could not open output config file \"%s\"", config_path); free(config_path); char *line = NULL; size_t len = 0; #ifndef USE_FGETLN ssize_t read; #endif bool head_of_file = true; /* write a header about auto-generation to the output file */ fputs("# This file has been auto-generated by i3-config-wizard(1).\n", ks_config); fputs("# It will not be overwritten, so edit it as you like.\n", ks_config); fputs("#\n", ks_config); fputs("# Should you change your keyboard layout some time, delete\n", ks_config); fputs("# this file and re-run i3-config-wizard(1).\n", ks_config); fputs("#\n", ks_config); #ifdef USE_FGETLN char *buf = NULL; while ((buf = fgetln(kc_config, &len)) != NULL) { /* fgetln does not return null-terminated strings */ FREE(line); sasprintf(&line, "%.*s", len, buf); #else size_t linecap = 0; while ((read = getline(&line, &linecap, kc_config)) != -1) { len = strlen(line); #endif /* skip the warning block at the beginning of the input file */ if (head_of_file && strncmp("# WARNING", line, strlen("# WARNING")) == 0) continue; head_of_file = false; /* Skip leading whitespace */ char *walk = line; while (isspace(*walk) && walk < (line + len)) { /* Pre-output the skipped whitespaces to keep proper indentation */ fputc(*walk, ks_config); walk++; } /* Set the modifier the user chose */ if (strncmp(walk, "set $mod ", strlen("set $mod ")) == 0) { if (modifier == MOD_Mod1) fputs("set $mod Mod1\n", ks_config); else fputs("set $mod Mod4\n", ks_config); continue; } /* Check for 'bindcode'. If it’s not a bindcode line, we * just copy it to the output file */ if (strncmp(walk, "bindcode", strlen("bindcode")) != 0) { fputs(walk, ks_config); continue; } char *result = rewrite_binding(walk); fputs(result, ks_config); free(result); } /* sync to do our best in order to have the file really stored on disk */ fflush(ks_config); fsync(fileno(ks_config)); #ifndef USE_FGETLN free(line); #endif fclose(kc_config); fclose(ks_config); /* tell i3 to reload the config file */ int sockfd = ipc_connect(socket_path); ipc_send_message(sockfd, strlen("reload"), 0, (uint8_t *)"reload"); close(sockfd); exit(0); } int main(int argc, char *argv[]) { config_path = resolve_tilde("~/.i3/config"); socket_path = getenv("I3SOCK"); char *pattern = "-misc-fixed-medium-r-normal--13-120-75-75-C-70-iso10646-1"; char *patternbold = "-misc-fixed-bold-r-normal--13-120-75-75-C-70-iso10646-1"; int o, option_index = 0; static struct option long_options[] = { {"socket", required_argument, 0, 's'}, {"version", no_argument, 0, 'v'}, {"limit", required_argument, 0, 'l'}, {"prompt", required_argument, 0, 'P'}, {"prefix", required_argument, 0, 'p'}, {"font", required_argument, 0, 'f'}, {"help", no_argument, 0, 'h'}, {0, 0, 0, 0}}; char *options_string = "s:vh"; while ((o = getopt_long(argc, argv, options_string, long_options, &option_index)) != -1) { switch (o) { case 's': FREE(socket_path); socket_path = strdup(optarg); break; case 'v': printf("i3-config-wizard " I3_VERSION "\n"); return 0; case 'h': printf("i3-config-wizard " I3_VERSION "\n"); printf("i3-config-wizard [-s <socket>] [-v]\n"); return 0; } } /* Check if the destination config file does not exist but the path is * writable. If not, exit now, this program is not useful in that case. */ struct stat stbuf; if (stat(config_path, &stbuf) == 0) { printf("The config file \"%s\" already exists. Exiting.\n", config_path); return 0; } /* Create ~/.i3 if it does not yet exist */ char *config_dir = resolve_tilde("~/.i3"); if (stat(config_dir, &stbuf) != 0) if (mkdir(config_dir, 0755) == -1) err(1, "mkdir(%s) failed", config_dir); free(config_dir); int fd; if ((fd = open(config_path, O_CREAT | O_RDWR, 0644)) == -1) { printf("Cannot open file \"%s\" for writing: %s. Exiting.\n", config_path, strerror(errno)); return 0; } close(fd); unlink(config_path); int screen; if ((conn = xcb_connect(NULL, &screen)) == NULL || xcb_connection_has_error(conn)) errx(1, "Cannot open display\n"); if (socket_path == NULL) socket_path = root_atom_contents("I3_SOCKET_PATH", conn, screen); if (socket_path == NULL) socket_path = "/tmp/i3-ipc.sock"; keysyms = xcb_key_symbols_alloc(conn); xcb_get_modifier_mapping_cookie_t modmap_cookie; modmap_cookie = xcb_get_modifier_mapping(conn); symbols = xcb_key_symbols_alloc(conn); /* Place requests for the atoms we need as soon as possible */ #define xmacro(atom) \ xcb_intern_atom_cookie_t atom##_cookie = xcb_intern_atom(conn, 0, strlen(#atom), #atom); #include "atoms.xmacro" #undef xmacro root_screen = xcb_aux_get_screen(conn, screen); root = root_screen->root; if (!(modmap_reply = xcb_get_modifier_mapping_reply(conn, modmap_cookie, NULL))) errx(EXIT_FAILURE, "Could not get modifier mapping\n"); xcb_numlock_mask = get_mod_mask_for(XCB_NUM_LOCK, symbols, modmap_reply); font = load_font(pattern, true); bold_font = load_font(patternbold, true); /* Open an input window */ win = xcb_generate_id(conn); xcb_create_window( conn, XCB_COPY_FROM_PARENT, win, /* the window id */ root, /* parent == root */ 490, 297, 300, 205, /* dimensions */ 0, /* X11 border = 0, we draw our own */ XCB_WINDOW_CLASS_INPUT_OUTPUT, XCB_WINDOW_CLASS_COPY_FROM_PARENT, /* copy visual from parent */ XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK, (uint32_t[]) { 0, /* back pixel: black */ XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_BUTTON_PRESS}); /* Map the window (make it visible) */ xcb_map_window(conn, win); /* Setup NetWM atoms */ #define xmacro(name) \ do { \ xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(conn, name##_cookie, NULL); \ if (!reply) \ errx(EXIT_FAILURE, "Could not get atom " #name "\n"); \ \ A_##name = reply->atom; \ free(reply); \ } while (0); #include "atoms.xmacro" #undef xmacro /* Set dock mode */ xcb_change_property(conn, XCB_PROP_MODE_REPLACE, win, A__NET_WM_WINDOW_TYPE, A_ATOM, 32, 1, (unsigned char *)&A__NET_WM_WINDOW_TYPE_DIALOG); /* Set window title */ xcb_change_property(conn, XCB_PROP_MODE_REPLACE, win, A__NET_WM_NAME, A_UTF8_STRING, 8, strlen("i3: first configuration"), "i3: first configuration"); /* Create pixmap */ pixmap = xcb_generate_id(conn); pixmap_gc = xcb_generate_id(conn); xcb_create_pixmap(conn, root_screen->root_depth, pixmap, win, 500, 500); xcb_create_gc(conn, pixmap_gc, pixmap, 0, 0); /* Grab the keyboard to get all input */ xcb_flush(conn); /* Try (repeatedly, if necessary) to grab the keyboard. We might not * get the keyboard at the first attempt because of the keybinding * still being active when started via a wm’s keybinding. */ xcb_grab_keyboard_cookie_t cookie; xcb_grab_keyboard_reply_t *reply = NULL; int count = 0; while ((reply == NULL || reply->status != XCB_GRAB_STATUS_SUCCESS) && (count++ < 500)) { cookie = xcb_grab_keyboard(conn, false, win, XCB_CURRENT_TIME, XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC); reply = xcb_grab_keyboard_reply(conn, cookie, NULL); usleep(1000); } if (reply->status != XCB_GRAB_STATUS_SUCCESS) { fprintf(stderr, "Could not grab keyboard, status = %d\n", reply->status); exit(-1); } xcb_flush(conn); xcb_generic_event_t *event; while ((event = xcb_wait_for_event(conn)) != NULL) { if (event->response_type == 0) { fprintf(stderr, "X11 Error received! sequence %x\n", event->sequence); continue; } /* Strip off the highest bit (set if the event is generated) */ int type = (event->response_type & 0x7F); switch (type) { case XCB_KEY_PRESS: handle_key_press(NULL, conn, (xcb_key_press_event_t *)event); break; /* TODO: handle mappingnotify */ case XCB_BUTTON_PRESS: handle_button_press((xcb_button_press_event_t *)event); break; case XCB_EXPOSE: handle_expose(); break; } free(event); } return 0; }
/******************** * dres_free_value ********************/ void dres_free_value(dres_value_t *val) { if (val && val->type == DRES_TYPE_STRING) FREE(val->v.s); }
/******************** * dres_free_field ********************/ void dres_free_field(dres_field_t *f) { FREE(f->name); dres_free_value(&f->value); }
int eGrep(int argc, char** argv){ Arguments* args = getArgs(argc, argv); int return_val = 0; short int quit = 0; if (args == NULL) { printf("Invalid command.\n"); return_val = 2; quit = 1; } if (!quit && !hasOption('q', args->options)) { // Command display printf("grep"); int i; for (i = 1; argv[i] != NULL; i++) printf(" %s", argv[i]); printf("\n"); for (i = 0; i < 50; i++) printf("-"); printf("\n"); // --- } else { #ifdef _WIN32 system("cls"); #else system("clear"); #endif } if (!quit && args->options != NULL && (*(Options*)args->options->data).name == '-' && args->files == NULL && args->pattern == NULL) { printf( "Usage : grep [OPTION] ... PATTERN [FILE]...\n" "Search for PATTERN or standard input in each FILE\n" "PATTERN is, by default, a standard regular expression (BRE) i.e \"hello world\".\n" "\nRegex selection :\n" "\n-E, --extended-regexp\tPattern is an extended regular expression (ERE)\n" "\n-e, --regexp=PATTERN\tuse PATTERN for matching\n" "\n-f, --file=FILE\t\tObtain PATTERN from file, the content of FILE is\n\t\t\tconsidered as the PATTERN to look for\n" "\n-i, --ignore-case\tIgnore case distinction\n" "\n-w, --word-regexp\tForce PATTERN to match only whole words\n" "\n-x, --line-regexp\tForce PATTERN to match only whole line\n" "\n-z, --null-data\t\tData lines end in 0 byte instead of a newline\n" "\nMiscellaneous :\n" "\n-s, --no-messages\tSuppress error messages\n" "\n-v, --invert-match\tSelect non-matching lines (uncompatible with -o)\n" "\n --help\t\tDisplay this help and exit\n" "\nOutput control :\n" "\n-m, --max-count=NUM\tStop searching in a file after NUM matching lines\n" "\n-b, --byte-offset\tPrint the byte offset for each output lines,\n" "\t\t\twhen combined with -o print the offset of the match\n" "\n-n, --line-number\tPrint line number with outuput lines (starts at 1)\n" "\n-H, --with-filename\tPrint the filename for each match (default when having\n\t\t\tmore than one FILE)\n" "\n-h, --no-filename\tSuppress the file name prefix on output (default when\n\t\t\thaving only one FILE)\n" "\n-o, --only-matching\tDisplays only the part of a line matching the pattern,\n" "\t\t\tin the case of multiple matches per line, displays\n\t\t\tas many lines as matches\n" "\t\t\tuncompatible with -v, -e and -E\n" "\n-q, --quiet, --silent\tSuppress all normal output\n" "\n-R, -r, --recursive\tSearch recursively in each files contained in FILE\n" "\n--include=GLOB\t\tSearch only files whose base name matches GLOB\n" "\n--exclude=GLOB\t\tSkip files whose base name matches GLOB\n" "\n--exclude-dir=DIR\tExclude directories matching the pattern DIR\n\t\t\tfrom recursive searches\n" "\n-L, --files-without-match Print only names of FILEs containing no match\n" "\n-l, --file-with-matches\tPrint only names of FILEs containing matches\n" "\n-c, --count\t\tprint only a count of matching lines per FILE\n" "\n-Z, --null\t\tPrint 0 byte after FILE name\n" "\nSpecial handling : if '-' is given as PATTERN, PATTERN become the standard input" "\nExit status :\n\n" "0 if no results were found\n" "1 if at least one result was found\n" "2 if an error was given\n\n" ); quit = 1; } if (!quit && args->options != NULL && (*(Options*)args->options->data).name == 'V' && args->files == NULL && args->pattern == NULL) { printf( "Grep command revised :\n\n" "version : %d.%d.%d\n\n" "authors :\n\tBASSET Cyril\n\tLAMBERTI Jean-Vincent\n\tPICARD David\n\n" ,GREP_STATUS,GREP_MAJOR_VERSION,GREP_MINOR_VERSION); quit = 1; } if(!quit && args->pattern == NULL) { if(!hasOption('s', args->options) && !hasOption('q', args->options)) printf("Pattern not found.\n"); return_val = 2; quit = 1; } if(!quit && (!args->files || !args->pattern)) quit = 1; if (!quit) { if (args->files != NULL) { Maillon* lines = NULL; int file_count = 0; if(hasOption('r',args->options)) { Maillon* files = NULL; Maillon* next = args->files; while(next != NULL) { getFileFrom((char*)next->data,&files,args->options); next = next->next; } lines = nFileLoader(files, hasOption('z',args->options)); file_count = listSize(files); } else { lines = nFileLoader(args->files, hasOption('z',args->options)); file_count = listSize(args->files); } if (lines != NULL) { Maillon* results = extractWithPattern(lines, args->pattern, args->options); if (!hasOption('q', args->options)) displayFileLine(results, file_count, args); return_val = listSize(results) > 0 ? 0 : 1 ; //listSize(results)>0?return_val=0:return_val=1; } } } if (args != NULL) { //freeList(&(args->options)); // Do not free pattern!!! It's the argv[i] address //freeList(&(args->files)); FREE(args); } return return_val; }
main(int argc, char **argv) { char *pagedir, *pagesubstr, *maskdir, *masksubstr; char *title, *fileout, *boxaafile, *boxaapath; l_int32 ret, res, type, thresh; l_float32 scalefactor; BOXAA *baa; static char mainName[] = "convertsegfilestopdf"; if (argc != 12) { fprintf(stderr, " Syntax: convertsegfilestopdf dirin substr res type thresh \\ \n" " boxaafile scalefactor title fileout\n" " where\n" " pagedir: input directory for image files\n" " pagesubstr: Use 'allfiles' to convert all files\n" " in the directory\n" " maskdir: input directory for mask files;\n" " use 'skip' to skip \n" " masksubstr: Use 'allfiles' to convert all files\n" " in the directory; 'skip' to skip\n" " res: Input resolution of each image;\n" " assumed to all be the same\n" " type: compression used for non-image regions:\n" " 0: default (G4 encoding)\n" " 1: JPEG encoding\n" " 2: G4 encoding\n" " 3: PNG encoding\n" " thresh: threshold for binarization; use 0 for default\n" " boxaafile: Optional file of 'image' regions within\n" " each page. This contains a boxa for each\n" " page, consisting of a set of regions.\n" " Use 'skip' to skip.\n" " scalefactor: Use to scale down the image regions\n" " title: Use 'none' to omit\n" " fileout: Output pdf file\n"); return 1; } pagedir = argv[1]; pagesubstr = argv[2]; maskdir = argv[3]; masksubstr = argv[4]; res = atoi(argv[5]); type = atoi(argv[6]); thresh = atoi(argv[7]); boxaafile = argv[8]; scalefactor = atof(argv[9]); title = argv[10]; fileout = argv[11]; if (!strcmp(pagesubstr, "allfiles")) pagesubstr = NULL; if (!strcmp(maskdir, "skip")) maskdir = NULL; if (!strcmp(masksubstr, "allfiles")) masksubstr = NULL; if (scalefactor <= 0.0 || scalefactor > 1.0) { L_WARNING("invalid scalefactor: setting to 1.0", mainName); scalefactor = 1.0; } if (type != 1 && type != 2 && type != 3) type = L_G4_ENCODE; if (thresh <= 0) thresh = 150; if (!strcmp(title, "none")) title = NULL; if (maskdir) /* use this; ignore any input boxaafile */ baa = convertNumberedMasksToBoxaa(maskdir, masksubstr, 0, 0); else if (strcmp(boxaafile, "skip")) { /* use the boxaafile */ boxaapath = genPathname(boxaafile, NULL); baa = boxaaRead(boxaapath); FREE(boxaapath); } else /* no maskdir and no input boxaafile */ baa = NULL; ret = convertSegmentedFilesToPdf(pagedir, pagesubstr, res, type, thresh, baa, 75, scalefactor, title, fileout); boxaaDestroy(&baa); return ret; }
static void llvm_pipeline_generic( struct draw_pt_middle_end *middle, const struct draw_fetch_info *fetch_info, const struct draw_prim_info *in_prim_info ) { struct llvm_middle_end *fpme = (struct llvm_middle_end *)middle; struct draw_context *draw = fpme->draw; struct draw_geometry_shader *gshader = draw->gs.geometry_shader; struct draw_prim_info gs_prim_info; struct draw_vertex_info llvm_vert_info; struct draw_vertex_info gs_vert_info; struct draw_vertex_info *vert_info; struct draw_prim_info ia_prim_info; struct draw_vertex_info ia_vert_info; const struct draw_prim_info *prim_info = in_prim_info; boolean free_prim_info = FALSE; unsigned opt = fpme->opt; unsigned clipped = 0; llvm_vert_info.count = fetch_info->count; llvm_vert_info.vertex_size = fpme->vertex_size; llvm_vert_info.stride = fpme->vertex_size; llvm_vert_info.verts = (struct vertex_header *)MALLOC(fpme->vertex_size * align(fetch_info->count, lp_native_vector_width / 32)); if (!llvm_vert_info.verts) { assert(0); return; } if (draw->collect_statistics) { draw->statistics.ia_vertices += fetch_info->count; draw->statistics.ia_primitives += u_decomposed_prims_for_vertices(prim_info->prim, prim_info->count); draw->statistics.vs_invocations += fetch_info->count; } if (fetch_info->linear) clipped = fpme->current_variant->jit_func( &fpme->llvm->jit_context, llvm_vert_info.verts, (const char **)draw->pt.user.vbuffer, fetch_info->start, fetch_info->count, fpme->vertex_size, draw->pt.vertex_buffer, draw->instance_id); else clipped = fpme->current_variant->jit_func_elts( &fpme->llvm->jit_context, llvm_vert_info.verts, (const char **)draw->pt.user.vbuffer, fetch_info->elts, fetch_info->count, fpme->vertex_size, draw->pt.vertex_buffer, draw->instance_id); /* Finished with fetch and vs: */ fetch_info = NULL; vert_info = &llvm_vert_info; if ((opt & PT_SHADE) && gshader) { struct draw_vertex_shader *vshader = draw->vs.vertex_shader; draw_geometry_shader_run(gshader, draw->pt.user.gs_constants, draw->pt.user.gs_constants_size, vert_info, prim_info, &vshader->info, &gs_vert_info, &gs_prim_info); FREE(vert_info->verts); vert_info = &gs_vert_info; prim_info = &gs_prim_info; } else { if (draw_prim_assembler_is_required(draw, prim_info, vert_info)) { draw_prim_assembler_run(draw, prim_info, vert_info, &ia_prim_info, &ia_vert_info); if (ia_vert_info.count) { FREE(vert_info->verts); vert_info = &ia_vert_info; prim_info = &ia_prim_info; free_prim_info = TRUE; } } } /* stream output needs to be done before clipping */ draw_pt_so_emit( fpme->so_emit, vert_info, prim_info ); /* * if there's no position, need to stop now, or the latter stages * will try to access non-existent position output. */ if (draw_current_shader_position_output(draw) != -1) { if ((opt & PT_SHADE) && gshader) { clipped = draw_pt_post_vs_run( fpme->post_vs, vert_info ); } if (clipped) { opt |= PT_PIPELINE; } /* Do we need to run the pipeline? Now will come here if clipped */ if (opt & PT_PIPELINE) { pipeline( fpme, vert_info, prim_info ); } else { emit( fpme->emit, vert_info, prim_info ); } } FREE(vert_info->verts); if (free_prim_info) { FREE(prim_info->primitive_lengths); } }
static void render_destroy( struct draw_stage *stage ) { FREE( stage ); }
/* * NAME: hfs->create() * DESCRIPTION: create and open a new file */ hfsfile *hfs_create(hfsvol *vol, const char *path, const char *type, const char *creator) { hfsfile *file = 0; unsigned long parid; char name[HFS_MAX_FLEN + 1]; CatKeyRec key; byte record[HFS_MAX_CATRECLEN]; unsigned reclen; int found; if (getvol(&vol) == -1) goto fail; file = ALLOC(hfsfile, 1); if (file == 0) ERROR(ENOMEM, 0); found = v_resolve(&vol, path, &file->cat, &parid, name, 0); if (found == -1 || parid == 0) goto fail; if (found) ERROR(EEXIST, 0); if (parid == HFS_CNID_ROOTPAR) ERROR(EINVAL, 0); if (vol->flags & HFS_VOL_READONLY) ERROR(EROFS, 0); /* create file `name' in parent `parid' */ if (bt_space(&vol->cat, 1) == -1) goto fail; f_init(file, vol, vol->mdb.drNxtCNID++, name); vol->flags |= HFS_VOL_UPDATE_MDB; file->parid = parid; /* create catalog record */ file->cat.u.fil.filUsrWds.fdType = d_getsl((const unsigned char *) type); file->cat.u.fil.filUsrWds.fdCreator = d_getsl((const unsigned char *) creator); file->cat.u.fil.filCrDat = d_mtime(time(0)); file->cat.u.fil.filMdDat = file->cat.u.fil.filCrDat; r_makecatkey(&key, file->parid, file->name); r_packcatrec(&key, &file->cat, record, &reclen); if (bt_insert(&vol->cat, record, reclen) == -1 || v_adjvalence(vol, file->parid, 0, 1) == -1) goto fail; /* package file handle for user */ file->next = vol->files; file->refs = 1; if (vol->files) vol->files->prev = file; vol->files = file; return file; fail: FREE(file); return 0; }
Task* import_heap_image (const char* fname, Heapcleaner_Args* params) { // ================= // Task* task; Heapfile_Header image_header; Heap_Header heap_header; Val *externs; Pthread_Image image; Inbuf inbuf; if (fname != NULL) { // // Resolve the name of the image. // If the file exists use it, otherwise try the // pathname with the machine ID as an extension. if ((inbuf.file = fopen(fname, "rb"))) { // if (verbosity > 0) say("loading %s ", fname); } else { // if ((inbuf.file = fopen(fname, "rb"))) { // if (verbosity > 0) say("loading %s ", fname); } else { die ("unable to open heap image \"%s\"\n", fname); } } inbuf.needs_to_be_byteswapped = FALSE; inbuf.buf = NULL; inbuf.nbytes = 0; } else { // // fname == NULL, so try to find // an in-core heap image: #if defined(DLOPEN) && !defined(OPSYS_WIN32) // void *lib = dlopen (NULL, RTLD_LAZY); void *vimg, *vimglenptr; if ((vimg = dlsym(lib,HEAP_IMAGE_SYMBOL )) == NULL) die("no in-core heap image found\n"); if ((vimglenptr = dlsym(lib,HEAP_IMAGE_LEN_SYMBOL)) == NULL) die("unable to find length of in-core heap image\n"); inbuf.file = NULL; inbuf.needs_to_be_byteswapped = FALSE; inbuf.base = vimg; inbuf.buf = inbuf.base; inbuf.nbytes = *(long*)vimglenptr; #else die("in-core heap images not implemented\n"); #endif } READ(&inbuf, image_header); if (image_header.byte_order != ORDER) die ("incorrect byte order in heap image\n"); if (image_header.magic != IMAGE_MAGIC) die ("bad magic number (%#x) in heap image\n", image_header.magic); if ((image_header.kind != EXPORT_HEAP_IMAGE) && (image_header.kind != EXPORT_FN_IMAGE)) die ("bad image kind (%d) in heap image\n", image_header.kind); READ(&inbuf, heap_header); // Check for command-line overrides of heap parameters: // if (params->agegroup0_buffer_bytesize == 0) { params->agegroup0_buffer_bytesize = heap_header.agegroup0_buffer_bytesize; } if (params->active_agegroups < heap_header.active_agegroups) { params->active_agegroups = heap_header.active_agegroups; } if (params->oldest_agegroup_keeping_idle_fromspace_buffers < 0) { params->oldest_agegroup_keeping_idle_fromspace_buffers = heap_header.oldest_agegroup_keeping_idle_fromspace_buffers; } task = make_task( FALSE, params ); // make_task def in src/c/main/runtime-state.c // Get the run-time pointers into the heap: // *PTR_CAST( Val*, PERVASIVE_PACKAGE_PICKLE_LIST_REFCELL__GLOBAL ) = heap_header.pervasive_package_pickle_list; // This carefully constructed fake looks like a normal // compiled package from the Mythryl side but actually // links to compile C code -- see the hack in // // src/c/main/load-compiledfiles.c // runtime_package__global = heap_header.runtime_pseudopackage; #ifdef ASM_MATH mathvec__global = heap_header.math_package; #endif externs = heapio__read_externs_table (&inbuf); // Read the externals table. READ(&inbuf, image); // Read and initialize the Mythryl state info. // if (image_header.kind == EXPORT_HEAP_IMAGE) { // Load the live registers: // ASSIGN( POSIX_INTERPROCESS_SIGNAL_HANDLER_REFCELL__GLOBAL, image.posix_interprocess_signal_handler ); // task->argument = image.stdArg; task->fate = image.stdCont; task->current_closure = image.stdClos; task->program_counter = image.pc; task->exception_fate = image.exception_fate; task->current_thread = image.current_thread; // task->callee_saved_registers[0] = image.calleeSave[0]; task->callee_saved_registers[1] = image.calleeSave[1]; task->callee_saved_registers[2] = image.calleeSave[2]; read_heap (&inbuf, &heap_header, task, externs); // Read the Mythryl heap. /* cleaner_messages_are_enabled__global = TRUE; */ // Cleaning messages are on by default for interactive images. } else { // EXPORT_FN_IMAGE Val function_to_run; Val program_name; Val args; // Restore the signal handler: // ASSIGN( POSIX_INTERPROCESS_SIGNAL_HANDLER_REFCELL__GLOBAL, image.posix_interprocess_signal_handler ); // Read the Mythryl heap: // task->argument = image.stdArg; read_heap (&inbuf, &heap_header, task, externs); // Initialize the calling context (taken from run_mythryl_function): // run_mythryl_function def in src/c/main/run-mythryl-code-and-runtime-eventloop.c // function_to_run = task->argument; // task->exception_fate = PTR_CAST( Val, handle_uncaught_exception_closure_v + 1 ); task->current_thread = HEAP_VOID; // task->fate = PTR_CAST( Val, return_to_c_level_c ); task->current_closure = function_to_run; // task->program_counter = task->link_register = GET_CODE_ADDRESS_FROM_CLOSURE( function_to_run ); // Set up the arguments to the imported function: // program_name = make_ascii_string_from_c_string(task, mythryl_program_name__global); args = make_ascii_strings_from_vector_of_c_strings (task, commandline_arguments); REC_ALLOC2(task, task->argument, program_name, args); // debug_say("arg = %#x : [%#x, %#x]\n", task->argument, GET_TUPLE_SLOT_AS_VAL(task->argument, 0), GET_TUPLE_SLOT_AS_VAL(task->argument, 1)); // Cleaner messages are off by // default for spawn_to_disk images: // cleaner_messages_are_enabled__global = FALSE; } FREE( externs ); if (inbuf.file) fclose (inbuf.file); if (verbosity > 0) say(" done\n"); return task; } // fun import_heap_image
/** * calculate_visibility - Are tree nodes visible * @param ctx Mailbox * @param max_depth Maximum depth to check * * this calculates whether a node is the root of a subtree that has visible * nodes, whether a node itself is visible, whether, if invisible, it has * depth anyway, and whether any of its later siblings are roots of visible * subtrees. while it's at it, it frees the old thread display, so we can * skip parts of the tree in mutt_draw_tree() if we've decided here that we * don't care about them any more. */ static void calculate_visibility(struct Context *ctx, int *max_depth) { struct MuttThread *tmp = NULL, *tree = ctx->tree; int hide_top_missing = C_HideTopMissing && !C_HideMissing; int hide_top_limited = C_HideTopLimited && !C_HideLimited; int depth = 0; /* we walk each level backwards to make it easier to compute next_subtree_visible */ while (tree->next) tree = tree->next; *max_depth = 0; while (true) { if (depth > *max_depth) *max_depth = depth; tree->subtree_visible = 0; if (tree->message) { FREE(&tree->message->tree); if (is_visible(tree->message, ctx)) { tree->deep = true; tree->visible = true; tree->message->display_subject = need_display_subject(ctx, tree->message); for (tmp = tree; tmp; tmp = tmp->parent) { if (tmp->subtree_visible) { tmp->deep = true; tmp->subtree_visible = 2; break; } else tmp->subtree_visible = 1; } } else { tree->visible = false; tree->deep = !C_HideLimited; } } else { tree->visible = false; tree->deep = !C_HideMissing; } tree->next_subtree_visible = tree->next && (tree->next->next_subtree_visible || tree->next->subtree_visible); if (tree->child) { depth++; tree = tree->child; while (tree->next) tree = tree->next; } else if (tree->prev) tree = tree->prev; else { while (tree && !tree->prev) { depth--; tree = tree->parent; } if (!tree) break; else tree = tree->prev; } } /* now fix up for the OPTHIDETOP* options if necessary */ if (hide_top_limited || hide_top_missing) { tree = ctx->tree; while (true) { if (!tree->visible && tree->deep && (tree->subtree_visible < 2) && ((tree->message && hide_top_limited) || (!tree->message && hide_top_missing))) { tree->deep = false; } if (!tree->deep && tree->child && tree->subtree_visible) tree = tree->child; else if (tree->next) tree = tree->next; else { while (tree && !tree->next) tree = tree->parent; if (!tree) break; else tree = tree->next; } } } }
static void load_file_banded_imp(const char *file, const char *band, int reset_location, int multilook) { char *old_file = NULL; if (curr->filename) { old_file = STRDUP(curr->filename); free(curr->filename); curr->filename = NULL; } reset_globals(reset_location); asfPrintStatus("\nLoading: %s\n", file); // start loading of the new file curr->filename = STRDUP(file); // strip off a trailing "." if (curr->filename[strlen(curr->filename)-1] == '.') curr->filename[strlen(curr->filename)-1] = '\0'; // Determine if the current file is a new file static char *last_file = NULL; int new_file = 0; if (!last_file) last_file = STRDUP(curr->filename); if (last_file && strcmp(last_file, curr->filename) != 0) { new_file = 1; FREE(last_file); last_file = STRDUP(curr->filename); } if (read_file(curr->filename, band, multilook, FALSE)) { int dummy; char lut[256]; static int tiff_lut_exists = 0; static int asf_colormap_exists = 0; char embedded_tiff_lut_file[1024]; char embedded_asf_colormap_file[1024]; char *lut_loc = (char *)MALLOC(sizeof(char)*(strlen(get_asf_share_dir())+128)); sprintf(lut_loc, "%s%clook_up_tables", get_asf_share_dir(), DIR_SEPARATOR); sprintf(embedded_tiff_lut_file,"%s%c%s", lut_loc, DIR_SEPARATOR, EMBEDDED_TIFF_COLORMAP_LUT_FILE); sprintf(embedded_asf_colormap_file, "%s%c%s", lut_loc, DIR_SEPARATOR, EMBEDDED_ASF_COLORMAP_LUT_FILE); FREE(lut_loc); tiff_lut_exists = new_file ? 0 : tiff_lut_exists; asf_colormap_exists = new_file ? 0 : asf_colormap_exists; tiff_lut_exists += fileExists(embedded_tiff_lut_file) ? 1 : 0; asf_colormap_exists += fileExists(embedded_asf_colormap_file) ? 1 : 0; GtkWidget *om = get_widget_checked("lut_optionmenu"); int idx = gtk_option_menu_get_history(GTK_OPTION_MENU(om)); if (tiff_lut_exists <= 1 && check_for_embedded_tiff_lut(curr->filename, &dummy, lut)) { // On first read of a TIFF file, check for embedded colormap and turn it into a // look up table if it exists ...then select it // (Run this stuff ONCE ...else the embedded lut will keep getting selected, even if changed) if (fileExists(embedded_asf_colormap_file)) { remove(embedded_asf_colormap_file); asf_colormap_exists = 0; } if (get_tiff_lut_index() == 0) { populate_lut_combo(); GtkWidget *option_menu = get_widget_checked("lut_optionmenu"); gtk_option_menu_set_history(GTK_OPTION_MENU(option_menu), get_tiff_lut_index()); set_current_index(get_tiff_lut_index()); select_lut(lut); } else { set_current_index(idx); } } else if (tiff_lut_exists && !check_for_embedded_tiff_lut(curr->filename, &dummy, lut)) { // If a tiff colormap look up table exists, but the current file being // read is not a color map tiff, then delete the existing tiff color map // look up table remove(embedded_tiff_lut_file); tiff_lut_exists = 0; populate_lut_combo(); // Re-populate since tiff colormap lut was removed GtkWidget *option_menu = get_widget_checked("lut_optionmenu"); gtk_option_menu_set_history(GTK_OPTION_MENU(option_menu), 0); // Default to None set_current_index(0); } if (asf_colormap_exists <= 1 && is_colormap_ASF_file(curr->filename)) { // On first read of an ASF file, check for a colormap and turn it into a // look up table if it exists ...then select it // (Run this stuff ONCE ...else the embedded lut will keep getting selected, even if changed) if (fileExists(embedded_tiff_lut_file)) { remove(embedded_tiff_lut_file); tiff_lut_exists = 0; } if (get_asf_lut_index() == 0) { populate_lut_combo(); select_lut(EMBEDDED_ASF_COLORMAP_LUT); GtkWidget *option_menu = get_widget_checked("lut_optionmenu"); gtk_option_menu_set_history(GTK_OPTION_MENU(option_menu), get_asf_lut_index()); set_current_index(get_asf_lut_index()); } else { set_current_index(idx); } } else if (asf_colormap_exists && !is_colormap_ASF_file(curr->filename)) { // If an ASF colormap look up table exists, but the current file being // read does not contain a color map in the metadata, then delete the existing ASF color map // look up table remove(embedded_asf_colormap_file); asf_colormap_exists = 0; populate_lut_combo(); // Re-populate since tiff colormap lut was removed GtkWidget *option_menu = get_widget_checked("lut_optionmenu"); gtk_option_menu_set_history(GTK_OPTION_MENU(option_menu), 0); // Default to None set_current_index(0); } if (new_file && !tiff_lut_exists && !asf_colormap_exists && reset_location && curr->meta && curr->meta->general) { // Change LUT selection if necessary set_lut_based_on_image_type(curr->meta->general->image_data_type); } else if (!new_file) { // Respect any changes made by the user to the look-up table selection after // the file has loaded the first time ... set_current_index(idx); } check_lut(); set_title(band != NULL, band); // load the metadata & image data, other setup fill_small_force_reload(curr); fill_big(curr); update_pixel_info(curr); update_zoom(); fill_meta_info(); fill_stats(curr); setup_bands_tab(curr->meta); FREE(old_file); } else { // file failed to load, re-load the old one // this is to prevent trying to re-load the old file again & again, // if for some reason that fails if (strcmp(curr->filename, old_file) == 0) { // if this does happen, just quit asfPrintError("Failed to load %s.\n", curr->filename); } asfPrintStatus("Failed to load %s. Re-loading %s.\n", curr->filename, old_file); load_file_banded_imp(old_file, band, reset_location, multilook); if (reset_location) { center_samp = (double)(curr->ns)/2.; center_line = (double)(curr->nl)/2.; crosshair_samp = (double)(curr->ns)/2.; crosshair_line = (double)(curr->nl)/2.; } } }
/** * mutt_draw_tree - Draw a tree of threaded emails * @param ctx Mailbox * * Since the graphics characters have a value >255, I have to resort to using * escape sequences to pass the information to print_enriched_string(). These * are the macros MUTT_TREE_* defined in mutt.h. * * ncurses should automatically use the default ASCII characters instead of * graphics chars on terminals which don't support them (see the man page for * curs_addch). */ void mutt_draw_tree(struct Context *ctx) { char *pfx = NULL, *mypfx = NULL, *arrow = NULL, *myarrow = NULL, *new_tree = NULL; enum TreeChar corner = (C_Sort & SORT_REVERSE) ? MUTT_TREE_ULCORNER : MUTT_TREE_LLCORNER; enum TreeChar vtee = (C_Sort & SORT_REVERSE) ? MUTT_TREE_BTEE : MUTT_TREE_TTEE; int depth = 0, start_depth = 0, max_depth = 0, width = C_NarrowTree ? 1 : 2; struct MuttThread *nextdisp = NULL, *pseudo = NULL, *parent = NULL, *tree = ctx->tree; /* Do the visibility calculations and free the old thread chars. * From now on we can simply ignore invisible subtrees */ calculate_visibility(ctx, &max_depth); pfx = mutt_mem_malloc(width * max_depth + 2); arrow = mutt_mem_malloc(width * max_depth + 2); while (tree) { if (depth) { myarrow = arrow + (depth - start_depth - (start_depth ? 0 : 1)) * width; if (depth && (start_depth == depth)) myarrow[0] = nextdisp ? MUTT_TREE_LTEE : corner; else if (parent->message && !C_HideLimited) myarrow[0] = MUTT_TREE_HIDDEN; else if (!parent->message && !C_HideMissing) myarrow[0] = MUTT_TREE_MISSING; else myarrow[0] = vtee; if (width == 2) { myarrow[1] = pseudo ? MUTT_TREE_STAR : (tree->duplicate_thread ? MUTT_TREE_EQUALS : MUTT_TREE_HLINE); } if (tree->visible) { myarrow[width] = MUTT_TREE_RARROW; myarrow[width + 1] = 0; new_tree = mutt_mem_malloc((2 + depth * width)); if (start_depth > 1) { strncpy(new_tree, pfx, (start_depth - 1) * width); mutt_str_strfcpy(new_tree + (start_depth - 1) * width, arrow, (1 + depth - start_depth) * width + 2); } else mutt_str_strfcpy(new_tree, arrow, 2 + depth * width); tree->message->tree = new_tree; } } if (tree->child && depth) { mypfx = pfx + (depth - 1) * width; mypfx[0] = nextdisp ? MUTT_TREE_VLINE : MUTT_TREE_SPACE; if (width == 2) mypfx[1] = MUTT_TREE_SPACE; } parent = tree; nextdisp = NULL; pseudo = NULL; do { if (tree->child && tree->subtree_visible) { if (tree->deep) depth++; if (tree->visible) start_depth = depth; tree = tree->child; /* we do this here because we need to make sure that the first child thread * of the old tree that we deal with is actually displayed if any are, * or we might set the parent variable wrong while going through it. */ while (!tree->subtree_visible && tree->next) tree = tree->next; } else { while (!tree->next && tree->parent) { if (tree == pseudo) pseudo = NULL; if (tree == nextdisp) nextdisp = NULL; if (tree->visible) start_depth = depth; tree = tree->parent; if (tree->deep) { if (start_depth == depth) start_depth--; depth--; } } if (tree == pseudo) pseudo = NULL; if (tree == nextdisp) nextdisp = NULL; if (tree->visible) start_depth = depth; tree = tree->next; if (!tree) break; } if (!pseudo && tree->fake_thread) pseudo = tree; if (!nextdisp && tree->next_subtree_visible) nextdisp = tree; } while (!tree->deep); } FREE(&pfx); FREE(&arrow); }
/* *************************************************************************** ** Store data for addin object. Returns handle (NULL if error). *************************************************************************** */ char* StoreObject(char* name, void* data) { static char *routine = "StoreObject"; int status = FAILURE; char *handle = NULL; TObject *node; static char buffer[255]; if (data == NULL) { JpmcdsErrMsg("%s: No data to store provided.\n", routine); goto done; } if (name == NULL) { JpmcdsErrMsg("%s: No object name provided.\n", routine); goto done; } if (strlen(name) > 200) { JpmcdsErrMsg("%s: Object name cannot exceed 200 characters.\n", routine); goto done; } node = FindNode(name); if (node == NULL) { node = NEW(TObject); if (node == NULL) goto done; node->name = strdup(name); node->version = 1; node->data = data; node->next = cache; cache = node; } else { node->version += 1; JpmcdsFreeTCurve((TCurve*)(node->data)); node->data = data; } sprintf(buffer, "%s%c%d\0", node->name, SEPARATOR, node->version); handle = strdup(buffer); if (handle == NULL) goto done; strcpy(handle, buffer); status = SUCCESS; done: if (status != SUCCESS) { JpmcdsErrMsg("%s: Failed!\n", routine); FREE(handle); handle = NULL; } return handle; }
static void fse_destroy(struct draw_pt_middle_end *middle) { FREE(middle); }
void free_derives() { FREE(derives[ntokens]); FREE(derives + ntokens); }
/** * Free all the temporary data in a scene. */ void lp_scene_end_rasterization(struct lp_scene *scene ) { int i, j; /* Unmap color buffers */ for (i = 0; i < scene->fb.nr_cbufs; i++) { if (scene->cbufs[i].map) { struct pipe_surface *cbuf = scene->fb.cbufs[i]; if (llvmpipe_resource_is_texture(cbuf->texture)) { llvmpipe_resource_unmap(cbuf->texture, cbuf->u.tex.level, cbuf->u.tex.first_layer); } scene->cbufs[i].map = NULL; } } /* Unmap z/stencil buffer */ if (scene->zsbuf.map) { struct pipe_surface *zsbuf = scene->fb.zsbuf; llvmpipe_resource_unmap(zsbuf->texture, zsbuf->u.tex.level, zsbuf->u.tex.first_layer); scene->zsbuf.map = NULL; } /* Reset all command lists: */ for (i = 0; i < scene->tiles_x; i++) { for (j = 0; j < scene->tiles_y; j++) { struct cmd_bin *bin = lp_scene_get_bin(scene, i, j); bin->head = NULL; bin->tail = NULL; bin->last_state = NULL; } } /* If there are any bins which weren't cleared by the loop above, * they will be caught (on debug builds at least) by this assert: */ assert(lp_scene_is_empty(scene)); /* Decrement texture ref counts */ { struct resource_ref *ref; int i, j = 0; for (ref = scene->resources; ref; ref = ref->next) { for (i = 0; i < ref->count; i++) { if (LP_DEBUG & DEBUG_SETUP) debug_printf("resource %d: %p %dx%d sz %d\n", j, (void *) ref->resource[i], ref->resource[i]->width0, ref->resource[i]->height0, llvmpipe_resource_size(ref->resource[i])); j++; pipe_resource_reference(&ref->resource[i], NULL); } } if (LP_DEBUG & DEBUG_SETUP) debug_printf("scene %d resources, sz %d\n", j, scene->resource_reference_size); } /* Free all scene data blocks: */ { struct data_block_list *list = &scene->data; struct data_block *block, *tmp; for (block = list->head->next; block; block = tmp) { tmp = block->next; FREE(block); } list->head->next = NULL; list->head->used = 0; } lp_fence_reference(&scene->fence, NULL); scene->resources = NULL; scene->scene_size = 0; scene->resource_reference_size = 0; scene->has_depthstencil_clear = FALSE; scene->alloc_failed = FALSE; util_unreference_framebuffer_state( &scene->fb ); }
void StringBuffer_free(T *S) { assert(S && *S); FREE((*S)->buffer); FREE(*S); }
// Efface un champ de bits void cbitDel(CBit s) { FREE(s); }
static krb5_error_code krb5_rc_dfl_expunge_locked(krb5_context context, krb5_rcache id) { struct dfl_data *t = (struct dfl_data *)id->data; #ifdef NOIOSTUFF int i; struct authlist **q; struct authlist **qt; struct authlist *r; struct authlist *rt; krb5_int32 now; if (krb5_timestamp(context, &now)) now = 0; for (q = &t->a; *q; q = qt) { qt = &(*q)->na; if (alive(now, &(*q)->rep, t->lifespan) == CMP_EXPIRED) { FREE((*q)->rep.client); FREE((*q)->rep.server); FREE(*q); *q = *qt; /* why doesn't this feel right? */ } } for (i = 0; i < t->hsize; i++) t->h[i] = (struct authlist *) 0; for (r = t->a; r; r = r->na) { i = hash(&r->rep, t->hsize); rt = t->h[i]; t->h[i] = r; r->nh = rt; } return 0; #else struct authlist *q; char *name; krb5_error_code retval = 0; krb5_rcache tmp; krb5_deltat lifespan = t->lifespan; /* save original lifespan */ if (! t->recovering) { name = t->name; t->name = 0; /* Clear name so it isn't freed */ (void) krb5_rc_dfl_close_no_free(context, id); retval = krb5_rc_dfl_resolve(context, id, name); free(name); if (retval) return retval; retval = krb5_rc_dfl_recover_locked(context, id); if (retval) return retval; t = (struct dfl_data *)id->data; /* point to recovered cache */ } tmp = (krb5_rcache) malloc(sizeof(*tmp)); if (!tmp) return ENOMEM; retval = krb5_rc_resolve_type(context, &tmp, "dfl"); if (retval) { free(tmp); return retval; } retval = krb5_rc_resolve(context, tmp, 0); if (retval) goto cleanup; retval = krb5_rc_initialize(context, tmp, lifespan); if (retval) goto cleanup; for (q = t->a; q; q = q->na) { if (krb5_rc_io_store(context, (struct dfl_data *)tmp->data, &q->rep)) { retval = KRB5_RC_IO; goto cleanup; } } /* NOTE: We set retval in case we have an error */ retval = KRB5_RC_IO; if (krb5_rc_io_sync(context, &((struct dfl_data *)tmp->data)->d)) goto cleanup; if (krb5_rc_io_sync(context, &t->d)) goto cleanup; if (krb5_rc_io_move(context, &t->d, &((struct dfl_data *)tmp->data)->d)) goto cleanup; retval = 0; cleanup: (void) krb5_rc_dfl_close(context, tmp); return retval; #endif }
/* * Create a new X/Mesa visual. * Input: display - X11 display * visinfo - an XVisualInfo pointer * rgb_flag - GL_TRUE = RGB mode, * GL_FALSE = color index mode * alpha_flag - alpha buffer requested? * db_flag - GL_TRUE = double-buffered, * GL_FALSE = single buffered * stereo_flag - stereo visual? * ximage_flag - GL_TRUE = use an XImage for back buffer, * GL_FALSE = use an off-screen pixmap for back buffer * depth_size - requested bits/depth values, or zero * stencil_size - requested bits/stencil values, or zero * accum_red_size - requested bits/red accum values, or zero * accum_green_size - requested bits/green accum values, or zero * accum_blue_size - requested bits/blue accum values, or zero * accum_alpha_size - requested bits/alpha accum values, or zero * num_samples - number of samples/pixel if multisampling, or zero * level - visual level, usually 0 * visualCaveat - ala the GLX extension, usually GLX_NONE * Return; a new XMesaVisual or 0 if error. */ PUBLIC XMesaVisual XMesaCreateVisual( Display *display, XVisualInfo * visinfo, GLboolean rgb_flag, GLboolean alpha_flag, GLboolean db_flag, GLboolean stereo_flag, GLboolean ximage_flag, GLint depth_size, GLint stencil_size, GLint accum_red_size, GLint accum_green_size, GLint accum_blue_size, GLint accum_alpha_size, GLint num_samples, GLint level, GLint visualCaveat ) { XMesaDisplay xmdpy = xmesa_init_display(display); XMesaVisual v; GLint red_bits, green_bits, blue_bits, alpha_bits; if (!xmdpy) return NULL; /* For debugging only */ if (_mesa_getenv("MESA_XSYNC")) { /* This makes debugging X easier. * In your debugger, set a breakpoint on _XError to stop when an * X protocol error is generated. */ XSynchronize( display, 1 ); } v = (XMesaVisual) CALLOC_STRUCT(xmesa_visual); if (!v) { return NULL; } v->display = display; /* Save a copy of the XVisualInfo struct because the user may Xfree() * the struct but we may need some of the information contained in it * at a later time. */ v->visinfo = (XVisualInfo *) MALLOC(sizeof(*visinfo)); if (!v->visinfo) { free(v); return NULL; } memcpy(v->visinfo, visinfo, sizeof(*visinfo)); v->ximage_flag = ximage_flag; v->mesa_visual.redMask = visinfo->red_mask; v->mesa_visual.greenMask = visinfo->green_mask; v->mesa_visual.blueMask = visinfo->blue_mask; v->visualID = visinfo->visualid; v->screen = visinfo->screen; #if !(defined(__cplusplus) || defined(c_plusplus)) v->visualType = xmesa_convert_from_x_visual_type(visinfo->class); #else v->visualType = xmesa_convert_from_x_visual_type(visinfo->c_class); #endif v->mesa_visual.visualRating = visualCaveat; if (alpha_flag) v->mesa_visual.alphaBits = 8; (void) initialize_visual_and_buffer( v, NULL, rgb_flag, 0, 0 ); { const int xclass = v->visualType; if (xclass == GLX_TRUE_COLOR || xclass == GLX_DIRECT_COLOR) { red_bits = _mesa_bitcount(GET_REDMASK(v)); green_bits = _mesa_bitcount(GET_GREENMASK(v)); blue_bits = _mesa_bitcount(GET_BLUEMASK(v)); } else { /* this is an approximation */ int depth; depth = v->visinfo->depth; red_bits = depth / 3; depth -= red_bits; green_bits = depth / 2; depth -= green_bits; blue_bits = depth; alpha_bits = 0; assert( red_bits + green_bits + blue_bits == v->visinfo->depth ); } alpha_bits = v->mesa_visual.alphaBits; } /* initialize visual */ { struct gl_config *vis = &v->mesa_visual; vis->rgbMode = GL_TRUE; vis->doubleBufferMode = db_flag; vis->stereoMode = stereo_flag; vis->redBits = red_bits; vis->greenBits = green_bits; vis->blueBits = blue_bits; vis->alphaBits = alpha_bits; vis->rgbBits = red_bits + green_bits + blue_bits; vis->indexBits = 0; vis->depthBits = depth_size; vis->stencilBits = stencil_size; vis->accumRedBits = accum_red_size; vis->accumGreenBits = accum_green_size; vis->accumBlueBits = accum_blue_size; vis->accumAlphaBits = accum_alpha_size; vis->haveAccumBuffer = accum_red_size > 0; vis->haveDepthBuffer = depth_size > 0; vis->haveStencilBuffer = stencil_size > 0; vis->numAuxBuffers = 0; vis->level = 0; vis->sampleBuffers = 0; vis->samples = 0; } v->stvis.buffer_mask = ST_ATTACHMENT_FRONT_LEFT_MASK; if (db_flag) v->stvis.buffer_mask |= ST_ATTACHMENT_BACK_LEFT_MASK; if (stereo_flag) { v->stvis.buffer_mask |= ST_ATTACHMENT_FRONT_RIGHT_MASK; if (db_flag) v->stvis.buffer_mask |= ST_ATTACHMENT_BACK_RIGHT_MASK; } v->stvis.color_format = choose_pixel_format(v); if (v->stvis.color_format == PIPE_FORMAT_NONE) { FREE(v->visinfo); FREE(v); return NULL; } v->stvis.depth_stencil_format = choose_depth_stencil_format(xmdpy, depth_size, stencil_size); v->stvis.accum_format = (accum_red_size + accum_green_size + accum_blue_size + accum_alpha_size) ? PIPE_FORMAT_R16G16B16A16_SNORM : PIPE_FORMAT_NONE; v->stvis.samples = num_samples; v->stvis.render_buffer = ST_ATTACHMENT_INVALID; /* XXX minor hack */ v->mesa_visual.level = level; return v; }
void initgrph(int showtitle) { int i; FILE *f; char *pigname; struct ws_event ws; struct ws_bitmap *cursor; inittimer(); #if defined (GNU_C) && defined (GO32) if ( showtitle && ws_initgrfx(640, 480, 256, init.fontname) && titlescreen() ) { ws_getevent(&ws, 1); } ws_textmode(); #endif if ( !w_initwins(init.xres, init.yres, 256, init.fontname) ) { printf(TXT_CANTINITWINS); my_exit(); } if ( ( f = fopen(init.menuname, "r") ) == NULL ) { fprintf(errf, TXT_NOMENUFILE, init.menuname); my_exit(); } my_assert( w_initmenu(f, do_event, ec_num_of_codes) ); fclose(f); pigname = pig.current_pigname; pig.current_pigname = NULL; newpigfile(pigname, NULL); FREE(pigname); /* draw the cursors (init the cursor data) */ cntrlcursor_ysize = altcursor_ysize = w_titlebarheight(); cntrlcursor_xsize = (ws_pixstrlen(TXT_TAG) + 2 + 3) / 4 * 4; altcursor_xsize = (ws_pixstrlen(TXT_INFO) + 2 + 3) / 4 * 4; cursor = ws_createbitmap(cntrlcursor_xsize, cntrlcursor_ysize, control_cursor); ws_bmdrawtext(cursor, 1, 0, cntrlcursor_xsize, TXT_TAG, 1, 0); ws_freebitmap(cursor); cursor = ws_createbitmap(altcursor_xsize, altcursor_ysize, alt_cursor); ws_bmdrawtext(cursor, 1, 0, altcursor_xsize, TXT_INFO, 1, 0); ws_freebitmap(cursor); cursor_initialized = 1; checkmem( pig.txt_buffer = MALLOC(64 * 64) ); memset(pig.txt_buffer, 0, 64 * 64); pig.txt_bm = ws_createbitmap(64, 64, pig.txt_buffer); checkmem( pig.door_buffer = MALLOC(64 * 64) ); memset(pig.door_buffer, 0, 64 * 64); pig.door_bm = ws_createbitmap(64, 64, pig.door_buffer); checkmem( pig.thing_buffer = MALLOC(64 * 64) ); memset(pig.thing_buffer, 0, 64 * 64); pig.thing_bm = ws_createbitmap(64, 64, pig.thing_buffer); button_win.xpos = w_xmaxwinsize() - button_win.xsize - 10; button_win.ypos = w_ymaxwinsize() - button_win.ysize - 10; if (init.d_ver >= d2_10_reg) { button_win.ypos -= 20; button_win.ysize += 20; if (init.d_ver >= d2_12_reg) { button_win.ypos -= 16; } button_win.ysize += 16; } checkmem( view.movewindow = w_openwindow(&button_win) ); drawallbuttons(view.movewindow); for (i = 0; i <= in_internal; i++) { makeoptwindow(i); } init_txtgrfx(); read_lightsources(); }
static void read_heap ( // ========= // Inbuf* bp, Heap_Header* header, Task* task, Val* externs ){ Heap* heap = task->heap; Sib_Header* sib_headers; Sib_Header* p; Sib_Header* q; int sib_headers_bytesize; int i, j, k; long prevSzB[MAX_PLAIN_ILKS], size; Sibid* oldBOOK2SIBID; Punt addrOffset[MAX_AGEGROUPS][MAX_PLAIN_ILKS]; Hugechunk_Region_Relocation_Info* boRelocInfo; Addresstable* boRegionTable; // Allocate a book_to_sibid__global for the imported // heap image's address space: // #ifdef TWO_LEVEL_MAP #error two level map not supported #else oldBOOK2SIBID = MALLOC_VEC (Sibid, BOOK2SIBID_TABLE_SIZE_IN_SLOTS); #endif // Read in the hugechunk region descriptors // for the old address space: // { int size; Hugechunk_Region_Header* boRgnHdr; boRegionTable = make_address_hashtable(LOG2_BOOK_BYTESIZE+1, header->hugechunk_ramregion_count); size = header->hugechunk_ramregion_count * sizeof(Hugechunk_Region_Header); boRgnHdr = (Hugechunk_Region_Header*) MALLOC (size); heapio__read_block( bp, boRgnHdr, size ); boRelocInfo = MALLOC_VEC(Hugechunk_Region_Relocation_Info, header->hugechunk_ramregion_count); for (i = 0; i < header->hugechunk_ramregion_count; i++) { set_book2sibid_entries_for_range(oldBOOK2SIBID, (Val*)(boRgnHdr[i].base_address), BOOKROUNDED_BYTESIZE(boRgnHdr[i].bytesize), HUGECHUNK_DATA_SIBID(1) ); oldBOOK2SIBID[GET_BOOK_CONTAINING_POINTEE(boRgnHdr[i].base_address)] = HUGECHUNK_RECORD_SIBID(MAX_AGEGROUPS); boRelocInfo[i].first_ram_quantum = boRgnHdr[i].first_ram_quantum; boRelocInfo[i].page_count = (boRgnHdr[i].bytesize - (boRgnHdr[i].first_ram_quantum - boRgnHdr[i].base_address)) >> LOG2_HUGECHUNK_RAM_QUANTUM_IN_BYTES; boRelocInfo[i].hugechunk_page_to_hugechunk = MALLOC_VEC(Hugechunk_Relocation_Info*, boRelocInfo[i].page_count); for (j = 0; j < boRelocInfo[i].page_count; j++) { // boRelocInfo[i].hugechunk_page_to_hugechunk[j] = NULL; } addresstable_insert (boRegionTable, boRgnHdr[i].base_address, &(boRelocInfo[i])); } FREE (boRgnHdr); } // Read the sib headers: // sib_headers_bytesize = header->active_agegroups * TOTAL_ILKS * sizeof( Sib_Header ); // sib_headers = (Sib_Header*) MALLOC( sib_headers_bytesize ); // heapio__read_block( bp, sib_headers, sib_headers_bytesize ); for (i = 0; i < MAX_PLAIN_ILKS; i++) { prevSzB[i] = heap->agegroup0_buffer_bytesize; } // Allocate the sib buffers and read in the heap image: // for (p = sib_headers, i = 0; i < header->active_agegroups; i++) { // Agegroup* age = heap->agegroup[ i ]; // Compute the space required for this agegroup, // and mark the oldBOOK2SIBID to reflect the old address space: // for (q = p, j = 0; j < MAX_PLAIN_ILKS; j++) { set_book2sibid_entries_for_range ( // oldBOOK2SIBID, (Val*) q->info.o.base_address, BOOKROUNDED_BYTESIZE( q->info.o.bytesize ), age->sib[ j ]->id ); size = q->info.o.bytesize + prevSzB[j]; if (j == PAIR_ILK && size > 0 ){ size += 2*WORD_BYTESIZE; } age->sib[ j ]->tospace_bytesize = BOOKROUNDED_BYTESIZE( size ); prevSzB[ j ] = q->info.o.bytesize; q++; } if (allocate_and_partition_an_agegroup(age) == FAILURE) { die ("unable to allocated space for agegroup %d\n", i+1); } if (sib_is_active( age->sib[ VECTOR_ILK ] )) { // sib_is_active def in src/c/h/heap.h // make_new_coarse_inter_agegroup_pointers_map_for_agegroup (age); } // Read in the sib buffers for this agegroup // and initialize the address offset table: // for (int j = 0; j < MAX_PLAIN_ILKS; j++) { // Sib* ap = age->sib[ j ]; if (p->info.o.bytesize > 0) { addrOffset[i][j] = (Punt)(ap->tospace) - (Punt)(p->info.o.base_address); heapio__seek( bp, (long) p->offset ); heapio__read_block( bp, (ap->tospace), p->info.o.bytesize ); ap->next_tospace_word_to_allocate = (Val *)((Punt)(ap->tospace) + p->info.o.bytesize); ap->end_of_fromspace_oldstuff = ap->tospace; } else if (sib_is_active(ap)) { ap->end_of_fromspace_oldstuff = ap->tospace; } if (verbosity > 0) say("."); p++; } // Read in the hugechunk sib buffers (currently just codechunks): // for (int ilk = 0; ilk < MAX_HUGE_ILKS; ilk++) { // MAX_HUGE_ILKS def in src/c/h/sibid.h // Punt totSizeB; Hugechunk* freeChunk; Hugechunk* bdp = NULL; // Without this initialization, gcc -Wall gives a 'possible uninitialized use' warning. Hugechunk_Region* free_region; Hugechunk_Header* boHdrs; int boHdrSizeB; int index; Hugechunk_Region_Relocation_Info* region; if (p->info.bo.hugechunk_quanta_count > 0) { // totSizeB = p->info.bo.hugechunk_quanta_count << LOG2_HUGECHUNK_RAM_QUANTUM_IN_BYTES; freeChunk = allocate_hugechunk_region( heap, totSizeB ); free_region = freeChunk->region; free_region->age_of_youngest_live_chunk_in_region = i; set_book2sibid_entries_for_range ( // book_to_sibid__global, (Val*) free_region, BYTESIZE_OF_MULTIPAGE_RAM_REGION( free_region->ram_region ), HUGECHUNK_DATA_SIBID( i ) ); book_to_sibid__global[ GET_BOOK_CONTAINING_POINTEE( free_region ) ] = HUGECHUNK_RECORD_SIBID( i ); // Read in the hugechunk headers: // boHdrSizeB = p->info.bo.hugechunk_count * sizeof(Hugechunk_Header); // boHdrs = (Hugechunk_Header*) MALLOC (boHdrSizeB); // heapio__read_block (bp, boHdrs, boHdrSizeB); // Read in the hugechunks: // heapio__read_block( bp, (void *)(freeChunk->chunk), totSizeB ); // if (ilk == CODE__HUGE_ILK) { // ilk = 0 == CODE__HUGE_ILK def in src/c/h/sibid.h // flush_instruction_cache ((void *)(freeChunk->chunk), totSizeB); } // Set up the hugechunk descriptors // and per-chunk relocation info: // for (k = 0; k < p->info.bo.hugechunk_count; k++) { // // Find the region relocation info for the // chunk's region in the exported heap: // for (index = GET_BOOK_CONTAINING_POINTEE(boHdrs[k].base_address); !SIBID_ID_IS_BIGCHUNK_RECORD(oldBOOK2SIBID[index]); index--) continue; region = LOOK_UP_HUGECHUNK_REGION (boRegionTable, index); // Allocate the hugechunk record for // the chunk and link it into the list // of hugechunks for its agegroup. // bdp = allocate_a_hugechunk( freeChunk, &(boHdrs[k]), region ); bdp->next = age->hugechunks[ ilk ]; age->hugechunks[ ilk ] = bdp; ASSERT( bdp->gen == i+1 ); if (codechunk_comment_display_is_enabled__global && ilk == CODE__HUGE_ILK ){ // Dump the comment string of the code chunk. Unt8* namestring; // if ((namestring = get_codechunk_comment_string_else_null( bdp ))) { debug_say ("[%6d bytes] %s\n", bdp->bytesize, (char*)namestring); } } } if (freeChunk != bdp) { // if p->info.bo.hugechunk_count can be zero, 'bdp' value here may be bogus. XXX BUGGO FIXME. // // There was some extra space left in the region: // insert_hugechunk_in_doubly_linked_list( heap->hugechunk_freelist, freeChunk); // insert_hugechunk_in_doubly_linked_list def in src/c/h/heap.h } FREE (boHdrs); } if (verbosity > 0) say("."); p++; } } repair_heap (heap, oldBOOK2SIBID, addrOffset, boRegionTable, externs); // Adjust the run-time globals // that point into the heap: // *PTR_CAST( Val*, PERVASIVE_PACKAGE_PICKLE_LIST_REFCELL__GLOBAL ) = repair_word( *PTR_CAST( Val*, PERVASIVE_PACKAGE_PICKLE_LIST_REFCELL__GLOBAL ), oldBOOK2SIBID, addrOffset, boRegionTable, externs ); runtime_package__global = repair_word( runtime_package__global, oldBOOK2SIBID, addrOffset, boRegionTable, externs ); #ifdef ASM_MATH mathvec__global = repair_word (mathvec__global, oldBOOK2SIBID, addrOffset, boRegionTable, externs); #endif // Adjust the Mythryl registers // to the new address space: // ASSIGN( POSIX_INTERPROCESS_SIGNAL_HANDLER_REFCELL__GLOBAL, // repair_word ( // DEREF( POSIX_INTERPROCESS_SIGNAL_HANDLER_REFCELL__GLOBAL ), oldBOOK2SIBID, addrOffset, boRegionTable, externs ) ); task->argument = repair_word( task->argument, oldBOOK2SIBID, addrOffset, boRegionTable, externs ); task->fate = repair_word( task->fate, oldBOOK2SIBID, addrOffset, boRegionTable, externs ); task->current_closure = repair_word( task->current_closure, oldBOOK2SIBID, addrOffset, boRegionTable, externs ); task->program_counter = repair_word( task->program_counter, oldBOOK2SIBID, addrOffset, boRegionTable, externs ); task->link_register = repair_word (task->link_register, oldBOOK2SIBID, addrOffset, boRegionTable, externs ); task->exception_fate = repair_word( task->exception_fate, oldBOOK2SIBID, addrOffset, boRegionTable, externs ); task->current_thread = repair_word( task->current_thread, oldBOOK2SIBID, addrOffset, boRegionTable, externs ); task->callee_saved_registers[0] = repair_word( task->callee_saved_registers[0], oldBOOK2SIBID, addrOffset, boRegionTable, externs ); task->callee_saved_registers[1] = repair_word( task->callee_saved_registers[1], oldBOOK2SIBID, addrOffset, boRegionTable, externs ); task->callee_saved_registers[2] = repair_word( task->callee_saved_registers[2], oldBOOK2SIBID, addrOffset, boRegionTable, externs ); // Release storage: // for (i = 0; i < header->hugechunk_ramregion_count; i++) { // Hugechunk_Relocation_Info* p; for (p = NULL, j = 0; j < boRelocInfo[i].page_count; j++) { if ((boRelocInfo[i].hugechunk_page_to_hugechunk[j] != NULL) && (boRelocInfo[i].hugechunk_page_to_hugechunk[j] != p)) { FREE (boRelocInfo[i].hugechunk_page_to_hugechunk[j]); p = boRelocInfo[i].hugechunk_page_to_hugechunk[j]; } } } free_address_table( boRegionTable, FALSE ); FREE( boRelocInfo ); FREE( sib_headers ); FREE( oldBOOK2SIBID ); // Reset the next_word_to_sweep_in_tospace pointers: // for (int i = 0; i < heap->active_agegroups; i++) { // Agegroup* age = heap->agegroup[i]; // for (int j = 0; j < MAX_PLAIN_ILKS; j++) { // Sib* ap = age->sib[ j ]; // if (sib_is_active(ap)) { // sib_is_active def in src/c/h/heap.h // ap->next_word_to_sweep_in_tospace = ap->next_tospace_word_to_allocate; } } } } // fun read_heap
int main(int argc, char** argv) { int opt,adc; char buffer[MAX_BUFFER]={0}; int fd; int res,c,counter,i,in; FILE *fp; float v_in,v_out; char *param_port = NULL; char *param_speed = NULL; char *param_imagefile=NULL; char *param_mode=NULL; char *param_backlight=NULL; BITMAPFILEHEADER header; BITMAPINFO *headerinfo; int headersize,bitmapsize; uint8_t *i_bits=NULL,*o_bits=NULL; // input bits array from original bitmap file, output bit as converted int chunksize=300 * 3 ; //default chunk of bytes to send must be set to max the device can handle without loss of data uint8_t b[3] ={0}; BOOL breakout=FALSE; BOOL verbose_mode=FALSE; BOOL has_more_data=TRUE; BOOL param_init=FALSE; BOOL show_image=FALSE; BOOL show_version=FALSE; BOOL test_pattern_full=FALSE; BOOL ADC_read=FALSE; printf("-----------------------------------------------------------------------------\n"); printf("\n"); printf(" BMP image sender for Nokia LCD Backpack V.0.3 \n"); printf(" Wiki Docs: http://dangerousprototypes.com/docs/Mathieu:_Another_LCD_backpack\n"); printf(" http://www.dangerousprototypes.com\n"); printf("\n"); printf("-----------------------------------------------------------------------------\n"); if (argc <= 1) { print_usage(argv[0]); exit(-1); } while ((opt = getopt(argc, argv, "iTtvVas:p:f:d:B:")) != -1) { switch (opt) { case 'p': // device eg. com1 com12 etc if ( param_port != NULL){ printf(" Device/PORT error!\n"); exit(-1); } param_port = strdup(optarg); break; case 'f': if (param_imagefile != NULL) { printf(" Invalid Parameter after Option -f \n"); exit(-1); } param_imagefile = strdup(optarg); break; case 's': if (param_speed != NULL) { printf(" Speed should be set: eg 921600 \n"); exit(-1); } param_speed = strdup(optarg); break; case 'B': // added new: chuck size should be multiply by 3 // 1 * 3 up to max of file size or max port speed? if ((atol(optarg) < MAX_BUFFER/3 )&&(atol(optarg)!=0) ) chunksize=atol(optarg)*3; else { printf(" Invalid chunk size parameter: using default: %i x 3 = %i Bytes\n",chunksize/3,chunksize); } break; case 'd': // dim the backlight if ( param_backlight != NULL){ printf(" Error: Parameter required to dim the backlight, Range: 0-100\n"); exit(-1); } param_backlight = strdup(optarg); break; case 'i': // initialize if (optarg!=NULL) { printf("Invalid option in -i\n"); } else { param_init=TRUE; } break; case 'V': //talk show some display if (optarg !=NULL) { printf("Invalid option in -V\n"); } else { verbose_mode=TRUE; } break; case 'v': // if (optarg !=NULL) { printf("Invalid option in -v\n"); } else { show_version=TRUE; } break; case 'T': // if (optarg !=NULL) { printf("Invalid option in -T\n"); } else { test_pattern_full=TRUE; } break; case 'a': // if (optarg !=NULL) { printf("Invalid option in -a\n"); } else { ADC_read=TRUE; } break; case 'h': print_usage(argv[0]); exit(-1); break; default: printf(" Invalid argument %c", opt); print_usage(argv[0]); exit(-1); break; } } if (param_port==NULL){ printf(" No serial port specified\n"); print_usage(argv[0]); exit(-1); } if (param_speed==NULL) param_speed=strdup("921600"); //default is 921600kbps fd = serial_open(param_port); if (fd < 0) { fprintf(stderr, " Error opening serial port\n"); return -1; } //setup port and speed serial_setup(fd,(speed_t) param_speed); if(param_init==TRUE) { // i Reset and initialize the LCD. buffer[0]='i'; serial_write( fd, buffer,1 ); printf(" LCD Initialized and reset\n"); } if(show_version==TRUE) { // i Reset and initialize the LCD. buffer[0]='v'; serial_write( fd, buffer,1 ); Sleep(1); res= serial_read(fd, buffer, sizeof(buffer)); printf(" Hardware/Software Version %s\n",buffer); } if(test_pattern_full==TRUE) { // i Reset and initialize the LCD. buffer[0]='T'; serial_write( fd, buffer,1 ); printf(" Test Pattern Command Send %c\n",buffer[0]); printf(" Hit any key to end test \n"); if (getch()) { buffer[0]=0x00; //any bytes to end serial_write( fd, buffer,1 ); } Sleep(1); res= serial_read(fd, buffer, sizeof(buffer)); printf(" Full Screen Test Ends: "); if(res==1 && buffer[0]==0x01 ){ printf(" Success!\n"); } else { printf(" Reply received: "); for (i=0;i <res;i++) printf(" %02x",(uint8_t) buffer[i]); printf("\n"); } } if( ADC_read==TRUE) { // LCD backlight voltage reading //Raw reading: 0x182 (386) //Actual voltage: (386/1024)*3.3volts=1.24volts //Scale for resistor divider: Vin = (Vout*(R1+R2))/R2 = (1.24volts*(18K+3.9K))/3.9K = 7.01volts (ideal is 7volts) buffer[0]='a'; serial_write( fd, buffer,1); printf(" ADC read command Send: %c \n",buffer[0]); Sleep(1); res= serial_read(fd, buffer, sizeof(buffer)); //expects 2 bytes at buffer[0] and buffer[1] printf(" Voltage Reading : "); for (i=0;i< res;i++) printf(" %02x",buffer[i]); adc = buffer[0] << 8; adc += buffer[1]; v_out=((float)(adc)/1024.0)*3.3; v_in = (1.24*(18000.0+3900.0))/3900.0; printf("= %2.2f",v_in); if((v_in>6.5) && (v_in<7.5)){ printf(" **PASS**\n"); }else{ printf(" FAIL!!!! :(\n"); } } if(param_backlight !=NULL) { // convert 0-100 to bytes, 0x00 - 0xff buffer[0]='d'; char dx=(atol(param_backlight)*255)/100; buffer[1]=dx; serial_write( fd, buffer,2 ); printf(" Dimlight Command Send: %c %c\n",buffer[0],buffer[1]); Sleep(1); res= serial_read(fd, buffer, sizeof(buffer)); printf(" Dim command reply: "); if(res==1 && buffer[0]==0x01 ){ printf(" Success!\n"); } else { printf(" Reply received: "); for (i=0;i <res;i++) printf(" %02x",(uint8_t) buffer[i]); printf("\n"); } } if (param_imagefile !=NULL) { show_image=TRUE; } if (show_image==TRUE) { //checks is needed to make sure this is a valid bmp file //open the Imagefile file if ((fp = fopen(param_imagefile, "rb")) == NULL) { printf(" Cannot open image file: %s\n",param_imagefile); exit(-1); } if (fread(&header, sizeof(BITMAPFILEHEADER), 1, fp) < 1){ printf(" Invalid Image file.. requires BMP file \n"); fclose(fp); exit(-1); } if (header.bfType != BF_TYPE) { //BM as signature printf("File: %s is not a valid bitmap file! \n ",param_imagefile); fclose(fp); exit(-1); } headersize = header.bfOffBits - sizeof(BITMAPFILEHEADER); // printf("Header.bfoffbits: %lu Sizeof Bitmapfilehader: %i Headersize is : %i\n",header.bfOffBits,sizeof(BITMAPFILEHEADER),headersize); if ((headerinfo = (BITMAPINFO *)malloc(headersize)) == NULL){ printf("Error allocating memory\n"); fclose(fp); exit(-1); } //error in debian here-> might be because I am using 64 bit if ((res=fread(headerinfo, 1, headersize, fp)) < headersize){ printf("Error: Headersize Error %i < %i\n",res,headersize ); fclose(fp); exit(-1); } printf(" Header size is %lu\n",headerinfo->bmiHeader.biSize); printf(" Image size is %lupx x %lupx\n",headerinfo->bmiHeader.biWidth,headerinfo->bmiHeader.biHeight); printf(" Number of colour planes is %d\n",headerinfo->bmiHeader.biPlanes); printf(" Bits per pixel is %d\n",headerinfo->bmiHeader.biBitCount); // printf(" Compression type is %lu\n",headerinfo->bmiHeader.biCompression); // printf(" Image size is %lu\n",headerinfo->bmiHeader.biSizeImage); // printf(" Number of colours is %lu\n",headerinfo->bmiHeader.biClrUsed); // printf(" Number of required colours is %lu\n",headerinfo->bmiHeader.biClrImportant); if ((bitmapsize = headerinfo->bmiHeader.biSizeImage) == 0){ bitmapsize = (headerinfo->bmiHeader.biWidth * headerinfo->bmiHeader.biBitCount + 7) / 8 * abs(headerinfo->bmiHeader.biHeight); } if ((i_bits = malloc(bitmapsize)) == NULL){ //allocate enough memory printf(" Error: Cannot allocate enough memory \n"); fclose(fp); exit(-1); } if ((o_bits = malloc(bitmapsize/2+1)) == NULL){ //allocate enough memory printf(" Error: Cannot allocate enough memory \n"); fclose(fp); exit(-1); } for (i=0;i < bitmapsize/2+1;i++) o_bits[i]=0x00; // make sure padding is there fclose(fp); fp = fopen(param_imagefile, "rb"); printf(" Offset to image data is %lu bytes\n",header.bfOffBits); //close and reopen bmp file //send the command //Send 'p' or 'P' send page of image data. printf(" Setting image mode \n"); buffer[0]='P'; serial_write( fd, buffer,1 ); fseek(fp,header.bfOffBits,SEEK_SET); //and disable this if above fgets is enabled if ((res=fread(i_bits,sizeof(unsigned char),bitmapsize,fp)) != bitmapsize) { printf(" Header information error: image data size inconsistent. %i %i\n",res,bitmapsize); fclose(fp); exit(-1); } printf(" Opening Port on %s at %sbps, using image file %s chunksize = %i X %i \n", param_port, param_speed,param_imagefile,chunksize/3,3); printf(" Ready to convert %d bit into 12 bit image data.. \n",headerinfo->bmiHeader.biBitCount); printf(" Press any key when ready...\n"); getch(); switch (headerinfo->bmiHeader.biBitCount) { case 1: printf(" 1 bit (black and white) not yet done"); fclose(fp); exit(-1); break; case 4: printf(" 4-bit (16 colors) not yet done"); fclose(fp); exit(-1); break; case 8: printf(" 8 bit (256 colors) not yet done"); fclose(fp); exit(-1); break; case 16: printf(" 16-bit not yet done"); fclose(fp); exit(-1); break; case 24: //convert i_bits to 12bits into o_bits counter=0; // counter for original bitmap data in=0; //counter for putting bytes in o_bits breakout=FALSE; while(1) { //the LCD needs 12bit color, this is 24bit //we need to discard the lower 4 bits of each byte //and pack six half bytes into 3 bytes to send the LCD //if we only have one pixel to process (3bytes) instead of 2, then the last should be 0 //need to do checks for end of data, make this more effecient //BMP byte order of BGR... //rrrrgggg bbbbrrrr ggggbbbb ... ggggbbbb //grab six bytes for (i=0;i < 6;i++){ if (counter > bitmapsize-1){ buffer[i]=0x00; //pad remaining then exit the loop breakout=TRUE; } else { buffer[i]=i_bits[counter++]; } if(verbose_mode==TRUE) printf(" %02x",(unsigned char) buffer[i]); } // convert to 4 bits each RGB if(verbose_mode==TRUE) printf("--->"); //R G b[0]=((buffer[2]&0xf0)|((buffer[1]>>4)&0x0f)); //B R2 b[1]=(buffer[0]&0xf0)|((buffer[5]>>4)&0x0f); //G2B2 b[2]=(buffer[4]&0xf0)|((buffer[3]>>4)&0x0f); // put in o_bits o_bits[in++] =b[0]; o_bits[in++] =b[1]; o_bits[in++] =b[2]; if(verbose_mode==TRUE) printf("%02X %02X %02X \n",b[0],b[1],b[2]); if (breakout==TRUE) { //try to clean if ((b[0]==0x00)&& (b[1] == 0x00)&& (b[2]==0x00)) { //remove excess padding in-=3; break; } } } break; case 32: printf(" 32-bit not yet done"); fclose(fp); exit(-1); break; default: printf(" Unrecognize Bit count \n"); fclose(fp); exit(-1); } printf(" sending image data..\n "); has_more_data=TRUE; i=0; while(i< in){ for (c=0; c < chunksize; c++) { if (i+c < in){ buffer[c]= o_bits[i+c]; } else { // no more data has_more_data=FALSE; break; //breakout of for loop, c has the last chunk } } if(verbose_mode==TRUE) { for(counter=0;counter < c;counter++) { printf(" [%i] %02X \n", i+counter, (uint8_t) buffer[counter]); // printf(" %02X \n", (uint8_t) buffer[counter]); } } serial_write( fd, buffer,c); i=i+c; if(has_more_data==FALSE) break; } printf(" Total Bytes Sent: %i\n",i); Sleep(1); res= serial_read(fd, buffer, sizeof(buffer)); if(res==1 && buffer[0]==0x01 ){ printf(" Success!\n"); } else { printf(" Reply received: "); for (i=0;i <res;i++) printf(" %02x",(uint8_t) buffer[i]); printf("\n"); } printf(" Done! :-)\n\n"); //close lcd fclose(fp); } serial_close(fd); FREE(param_port); FREE(param_speed); FREE(param_imagefile); FREE(param_mode); return 0; } //end main()
/* * NAME: hfs->mount() * DESCRIPTION: open an HFS volume; return volume descriptor or 0 (error) */ hfsvol *hfs_mount(const char *path, int pnum, int mode) { hfsvol *vol, *check; /* see if the volume is already mounted */ for (check = hfs_mounts; check; check = check->next) { if (check->pnum == pnum && v_same(check, path) == 1) { /* verify compatible read/write mode */ if (((check->flags & HFS_VOL_READONLY) && ! (mode & HFS_MODE_RDWR)) || (! (check->flags & HFS_VOL_READONLY) && (mode & (HFS_MODE_RDWR | HFS_MODE_ANY)))) { vol = check; goto done; } } } vol = ALLOC(hfsvol, 1); if (vol == 0) ERROR(ENOMEM, 0); v_init(vol, mode); /* open the medium */ switch (mode & HFS_MODE_MASK) { case HFS_MODE_RDWR: case HFS_MODE_ANY: if (v_open(vol, path, HFS_MODE_RDWR) != -1) break; if ((mode & HFS_MODE_MASK) == HFS_MODE_RDWR) goto fail; case HFS_MODE_RDONLY: default: vol->flags |= HFS_VOL_READONLY; if (v_open(vol, path, HFS_MODE_RDONLY) == -1) goto fail; } /* mount the volume */ if (v_geometry(vol, pnum) == -1 || v_mount(vol) == -1) goto fail; /* add to linked list of volumes */ vol->prev = 0; vol->next = hfs_mounts; if (hfs_mounts) hfs_mounts->prev = vol; hfs_mounts = vol; done: ++vol->refs; curvol = vol; return vol; fail: if (vol) { v_close(vol); FREE(vol); } return 0; }