text
stringlengths
2
104M
meta
dict
import React from 'react' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import * as Icons from '@fortawesome/free-solid-svg-icons' class StatusItem extends React.PureComponent { render () { const item = this.props.item return ( <div className='item' key={item.id}> {item.error && ( <a onClick={() => this.props.onClear()} title='Click to clear'> <FontAwesomeIcon icon={Icons.faTimesCircle} color='red' /> </a> )} {item.success && ( <a onClick={() => this.props.onClear()} title='Click to clear'> <FontAwesomeIcon icon={Icons.faCheckCircle} color='green' /> </a> )} {!item.error && !item.success && ( <a onClick={() => this.props.onClear()} title='Click to clear'> <FontAwesomeIcon icon={Icons.faSpinner} pulse /> </a> )} &nbsp;<span className='mainLabel'>({item.mainLabel})</span>{' '} <span className='label'>{item.label}</span> &nbsp;{item.error && ( <span> <span className='errorMessage'>{item.errorMessage}</span>&nbsp; <a onClick={() => this.props.onRetry()} title='Click to retry'> <FontAwesomeIcon icon={Icons.faRedo} /> </a> </span> )} </div> ) } } export default StatusItem
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
/** * * Status * */ import React from 'react'; import StatusItem from './statusItem'; /* eslint-disable react/prefer-stateless-function */ class Status extends React.PureComponent { render () { return ( <div className='status'> {Object.values(this.props.status.items) .sort((item1, item2) => item1.time - item2.time) .map(item => ( <StatusItem item={item} key={item.id} onClear={() => this.props.statusActions.clear(item.id)} onRetry={() => this.props.statusActions.retry(item.id)} /> ))} </div> ) } } Status.propTypes = {} export default Status
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
// @flow import React from 'react'; import { Alert, Button, Modal } from 'react-bootstrap'; export default class AbstractModal extends React.PureComponent { constructor(props, dialogClassName, initialState={}) { super(props) this.dialogClassName = dialogClassName initialState.loading = undefined initialState.error = undefined this.state = initialState this.setLoading = this.setLoading.bind(this) this.setError = this.setError.bind(this) } loading(loadingMessage, promise) { this.state.loading = loadingMessage this.state.error = undefined return promise.then(result => this.setLoading(false)).catch(error => this.setError(error.message)) } setLoading(loadingMessage) { this.setState({ loading: loadingMessage }) console.log('setLoading:'+loadingMessage) } isLoading() { return this.state.loading } isError() { return this.state.error } setError(errorMessage) { this.setState({ loading: false, error: errorMessage }) } renderTitle() { // to be overriden return <div/> } renderBody() { // to be overriden return <div/> } renderButtons() { // to be overriden return <div/> } render() { return ( <Modal show={true} onHide={this.props.onClose} dialogClassName={this.dialogClassName}> <Modal.Header> <Modal.Title>{this.renderTitle()}</Modal.Title> </Modal.Header> <Modal.Body> {this.renderBody()} </Modal.Body> <Modal.Footer> {this.state.loading && <div className="modal-status"> <div className="spinner-border spinner-border-sm" role="status"/> {this.state.loading} </div>} {!this.state.loading && this.state.error && <div className="modal-status"> <Alert variant='danger'>{this.state.error}</Alert> </div>} <Button variant="secondary" onClick={this.props.onClose}>Close</Button> {!this.state.loading && !this.state.error && this.renderButtons()} </Modal.Footer> </Modal> ); } }
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
// @flow import React from 'react'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import QRCode from 'qrcode.react'; import AbstractModal from './AbstractModal'; import { Button } from 'react-bootstrap'; export default class ZpubModal extends AbstractModal { constructor(props) { const initialState = {} super(props, 'modal-zpub', initialState) } renderTitle() { return <span>ZPUB</span> } renderButtons() { return <div/> } renderBody() { return <div className='row'> <div className='col-sm-12'> This is your ZPUB for <strong>{this.props.account}</strong>. Keep it confidential. <div className='text-center'> <QRCode className='qr' value={this.props.zpub} /><br/> <b>{this.props.zpub}</b> </div> </div> </div> } }
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
// @flow import React from 'react'; import walletService from '../../services/walletService'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import QRCode from 'qrcode.react'; import * as Icons from '@fortawesome/free-solid-svg-icons'; import AbstractModal from './AbstractModal'; import { Button } from 'react-bootstrap'; import poolsService from '../../services/poolsService'; import utils from '../../services/utils'; export default class DepositModal extends AbstractModal { constructor(props) { const initialState = { depositAddress: undefined } super(props, 'modal-deposit', initialState) this.handleNextDepositAddress = this.handleNextDepositAddress.bind(this) // fetch deposit address this.doFetchDepositAddressAndShow() } doFetchDepositAddressAndShow(distinct=false) { const setState = depositAddressResponse => { this.setState({ depositAddress: depositAddressResponse }) } if (distinct) { this.loading("Fetching another deposit address...", walletService.fetchDepositAddressDistinct(this.state.depositAddress).then(setState)) } else { this.loading("Fetching deposit address...", walletService.fetchDepositAddress().then(setState)) } } handleNextDepositAddress() { this.doFetchDepositAddressAndShow(true) } renderTitle() { return <span>Deposit</span> } renderButtons() { return <div> {!this.isLoading() && <Button onClick={this.handleNextDepositAddress}>Renew address <FontAwesomeIcon icon={Icons.faRedo} /></Button>} </div> } renderBody() { return <div> {!this.isLoading() && !this.isError() && ( <div> <div className='row'> <div className='col-sm-12'> Deposit funds to your deposit wallet: <div className='text-center'> <QRCode className='qr' value={this.state.depositAddress} /><br/> <b>{this.state.depositAddress}</b> </div><br/> </div> </div> <div className='row'> <div className='col-sm-2'></div> <div className='col-sm-8'> <table className='pools table table-sm text-center'> <thead> <tr> <th>Name</th> <th>Denomination</th> <th>Min. deposit</th> </tr> </thead> <tbody> {poolsService.getPools().map((pool,i) => <tr key={i}> <td>{pool.poolId}</td> <td>{utils.toBtc(pool.denomination)}</td> <td>{utils.toBtc(pool.tx0BalanceMin)}</td> </tr>)} </tbody> </table> </div> </div> <div className='col-sm-2'></div> </div> )} </div> } }
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
// @flow import React from 'react'; import AbstractModal from './AbstractModal'; import Webcam from 'react-webcam'; import QrcodeDecoder from 'qrcode-decoder'; const qr = new QrcodeDecoder(); type Props = {}; export default class WebcamPayloadModal extends AbstractModal { webcamRef = React.createRef<Webcam>(); captureInterval: IntervalID | null = null; constructor(props: Props) { const initialState = {}; super(props, 'modal-webcam-payload', initialState); } componentDidMount() { this.captureInterval = setInterval(this.captureImage, 2000); } componentWillUnmount() { if (this.captureInterval) { clearInterval(this.captureInterval); } } captureImage = async () => { if (this.webcamRef.current) { const imageData = this.webcamRef.current.getScreenshot(); if (imageData) { const result = await qr.decodeFromImage(imageData).catch(err => { console.log('QR code not readable: ', err); }); if (result) { this.props.onScan(result.data); this.props.onClose(); } } } }; renderTitle() { return <span>Scan your pairing payload</span>; } renderButtons() { return <div />; } renderBody() { return ( <div className="row"> <div className="col-sm-12"> Get your <strong>pairing payload</strong> from Samourai Wallet, go to <strong>Settings/Transactions/Experimental</strong> <div className="text-center pt-4"> <Webcam ref={this.webcamRef} audio={false} width={300} height={300} screenshotQuality={1} screenshotFormat={'image/png'} videoConstraints={{ width: 300, height: 300, facingMode: 'user' }} /> </div> </div> </div> ); } }
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
// @flow import React from 'react'; import { Button } from 'react-bootstrap'; import * as Icon from 'react-feather'; import utils from '../../services/utils'; import mixService from '../../services/mixService'; import AbstractModal from './AbstractModal'; import poolsService from '../../services/poolsService'; import { TX0_FEE_TARGET } from '../../const'; import backendService from '../../services/backendService'; export default class Tx0Modal extends AbstractModal { constructor(props) { const initialState = { pools: undefined, feeTarget: TX0_FEE_TARGET.BLOCKS_2.value, poolId: props.utxo.poolId, mixsTarget: props.utxo.mixsTargetOrDefault } super(props, 'modal-tx0', initialState) console.log('Tx0Modal', initialState) this.handleChangeFeeTarget = this.handleChangeFeeTarget.bind(this); this.handleChangePoolTx0 = this.handleChangePoolTx0.bind(this); this.handleChangeMixsTargetTx0 = this.handleChangeMixsTargetTx0.bind(this); this.handleSubmitTx0 = this.handleSubmitTx0.bind(this) this.fetchPoolsForTx0FeeTarget = this.fetchPoolsForTx0FeeTarget.bind(this) this.setStateWithTx0Preview = this.setStateWithTx0Preview.bind(this) this.fetchPoolsForTx0FeeTarget(initialState.feeTarget) } fetchPoolsForTx0FeeTarget(tx0FeeTarget) { // fetch pools for tx0 feeTarget this.loading("Fetching pools for tx0...", poolsService.fetchPoolsForTx0(this.props.utxo.value, tx0FeeTarget).then(pools => { if (pools.length == 0) { this.setError("No pool for this utxo and miner fee.") } const defaultPoolId = pools.length > 0 ? pools[0].poolId : undefined // preserve active poolId if still available const poolId = (this.state.poolId && pools.filter(p => p.poolId === this.state.poolId).length > 0) ? this.state.poolId : defaultPoolId return this.setStateWithTx0Preview({ poolId: poolId, pools: pools }) })) } setStateWithTx0Preview(newState) { const fullState = Object.assign(this.state, newState) if (!fullState.feeTarget || !fullState.poolId) { // cannot preview yet newState.tx0Preview = undefined this.setState( newState ) return Promise.resolve() } return this.loading("Fetching tx0 data...", backendService.utxo.tx0Preview(this.props.utxo.hash, this.props.utxo.index, fullState.feeTarget, fullState.poolId).then(tx0Preview => { newState.tx0Preview = tx0Preview this.setState( newState ) })) } handleChangeFeeTarget(e) { const feeTarget = e.target.value this.setStateWithTx0Preview({ feeTarget: feeTarget }) this.fetchPoolsForTx0FeeTarget(feeTarget) } handleChangePoolTx0(e) { const poolId = e.target.value this.setStateWithTx0Preview({ poolId: poolId }) } handleChangeMixsTargetTx0(e) { const mixsTarget = parseInt(e.target.value) this.setState({ mixsTarget: mixsTarget }) } handleSubmitTx0() { mixService.tx0(this.props.utxo, this.state.feeTarget, this.state.poolId, this.state.mixsTarget) this.props.onClose(); } renderTitle() { return <div> Send to Premix </div> } renderButtons() { return <Button onClick={this.handleSubmitTx0}>Premix <Icon.ChevronsRight size={12}/></Button> } renderBody() { return <div> This will send <strong>{utils.toBtc(this.props.utxo.value)}btc</strong> to Premix and prepare for mixing.<br/> Spending <strong>{this.props.utxo.hash}:{this.props.utxo.index}</strong><br/> <br/> {!this.isLoading() && !this.isError() && <div> Pool fee: {this.state.tx0Preview && <span><strong>{utils.toBtc(this.state.tx0Preview.feeValue)} btc</strong></span>} <select className="form-control" onChange={this.handleChangePoolTx0} defaultValue={this.state.poolId}> {this.state.pools.map(pool => <option key={pool.poolId} value={pool.poolId}>{pool.poolId} · denomination: {utils.toBtc(pool.denomination)} btc · fee: {utils.toBtc(pool.feeValue)} btc</option>)} </select><br/> Miner fee: {this.state.tx0Preview && <strong>{utils.toBtc(this.state.tx0Preview.minerFee)} btc</strong>} <select className="form-control" onChange={this.handleChangeFeeTarget} defaultValue={this.state.feeTarget}> {Object.keys(TX0_FEE_TARGET).map(feeTargetKey => { const feeTargetItem = TX0_FEE_TARGET[feeTargetKey] return <option key={feeTargetItem.value} value={feeTargetItem.value}>{feeTargetItem.label}</option> })} </select><br/> Mixs target: (editable later) <select className="form-control col-sm-2" onChange={this.handleChangeMixsTargetTx0} defaultValue={this.state.mixsTarget}> <option value={1}>1</option> <option value={2}>2</option> <option value={3}>3</option> <option value={5}>5</option> <option value={10}>10</option> <option value={0}>∞</option> </select><br/> {this.state.tx0Preview && <div> This will generate <strong>{this.state.tx0Preview.nbPremix} premixs</strong> of <strong>{utils.toBtc(this.state.tx0Preview.premixValue)} btc</strong> + <strong>{utils.toBtc(this.state.tx0Preview.changeValue)} btc</strong> change </div>} </div>} </div> } }
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
/** * * Status * */ import React from 'react'; import {ProgressBar} from 'react-bootstrap'; import mixService from '../../services/mixService'; import utils from '../../services/utils'; import * as Icon from 'react-feather'; import poolsService from '../../services/poolsService'; /* eslint-disable react/prefer-stateless-function */ class MixStatus extends React.PureComponent { render () { return ( <div> <div className='row no-gutters'> <div className='col-sm-1 mixStatus align-self-center'> <div><strong>{mixService.getNbMixing()}</strong> mixing<br/> <strong>{mixService.getNbQueued()}</strong> queued</div> </div> <div className='col-sm-10 mixThreads'> <div className='row no-gutters justify-content-center'> {mixService.getThreads().map((utxo,i) => { const pool = poolsService.findPool(utxo.poolId) const poolInfo = pool ? <small> • {pool.nbConfirmed}/{pool.mixAnonymitySet} peers</small> : undefined const message = utils.utxoMessage(utxo) let progressLabel = <div> <small>{utils.toBtc(utxo.value)}</small> <strong>{utils.statusLabel(utxo)}</strong>{poolInfo ? poolInfo : ''}<br/> {message && <small>{message}</small>} </div> const progressPercent = utxo.progressPercent ? utxo.progressPercent : 0 const progressVariant = utxo.progressPercent ? undefined : 'info' const poolProgress = pool ? (100 - progressPercent) * poolsService.computePoolProgress(pool) / 100 : undefined return <div className='col-sm-3 align-self-center' key={i}> <div className='row no-gutters'> <div className='col-sm-12 item'> <div className='label' title={utxo.hash + ':' + utxo.index + ' (' + utxo.account + ') (' + mixService.computeLastActivity(utxo) + ')'}>{progressLabel}</div> <ProgressBar> <ProgressBar animated now={progressPercent} variant={progressVariant} key={1} className={'progressBarSamourai' + (utxo.mixStep === 'CONNECTING' ? ' connecting' : '')}/> {poolProgress != undefined && <ProgressBar variant="warning" now={poolProgress} key={2}/>} </ProgressBar> </div> </div> </div> })} </div> </div> <div className='col-sm-1 mixStatus align-self-center text-center'> {mixService.isStarted() && <button className='btn btn-primary' onClick={() => mixService.stopMix()}><Icon.Square size={12}/> Stop</button>} {!mixService.isStarted() && <button className='btn btn-primary' onClick={() => mixService.startMix()}><Icon.Play size={12}/> Start</button>} </div> </div> </div> ) } } export default MixStatus
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
// @flow import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import { createHashHistory } from 'history'; import { routerMiddleware } from 'connected-react-router'; import createRootReducer from '../reducers'; const history = createHashHistory(); const rootReducer = createRootReducer(history); const router = routerMiddleware(history); const enhancer = applyMiddleware(thunk, router); function configureStore(initialState?) { return createStore(rootReducer, initialState, enhancer); } export default { configureStore, history };
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
import { createStore, applyMiddleware, compose } from 'redux'; import thunk from 'redux-thunk'; import { createHashHistory } from 'history'; import { routerMiddleware, routerActions } from 'connected-react-router'; import { createLogger } from 'redux-logger'; import createRootReducer from '../reducers'; const history = createHashHistory(); const rootReducer = createRootReducer(history); const configureStore = (initialState?) => { // Redux Configuration const middleware = []; const enhancers = []; // Thunk Middleware middleware.push(thunk); // Logging Middleware const logger = createLogger({ level: 'info', collapsed: true }); // Skip redux logs in console during the tests if (process.env.NODE_ENV !== 'test') { middleware.push(logger); } // Router Middleware const router = routerMiddleware(history); middleware.push(router); // Redux DevTools Configuration const actionCreators = { ...routerActions }; // If Redux DevTools Extension is installed use it, otherwise use Redux compose /* eslint-disable no-underscore-dangle */ const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({ // Options: http://extension.remotedev.io/docs/API/Arguments.html actionCreators }) : compose; /* eslint-enable no-underscore-dangle */ // Apply Middleware & Compose Enhancers enhancers.push(applyMiddleware(...middleware)); const enhancer = composeEnhancers(...enhancers); // Create Store const store = createStore(rootReducer, initialState, enhancer); if (module.hot) { module.hot.accept( '../reducers', // eslint-disable-next-line global-require () => store.replaceReducer(require('../reducers').default) ); } return store; }; export default { configureStore, history };
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
// @flow import configureStoreDev from './configureStore.dev'; import configureStoreProd from './configureStore.prod'; const selectedConfigureStore = process.env.NODE_ENV === 'production' ? configureStoreProd : configureStoreDev; export const { configureStore } = selectedConfigureStore; export const { history } = selectedConfigureStore;
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
import log from 'electron-log' import findLogPath from "electron-log/lib/transports/file/findLogPath"; import electron from "electron"; export const computeLogPath = (fileName) => { const app = (electron.app || electron.remote.app) return findLogPath(app.getName(), fileName) } const GUI_LOG_FILENAME='whirlpool-gui.log' class Logger { constructor(fileName, level='info') { log.transports.file.fileName = fileName this.setLevel(level) } error(...args) { return log.error(...args) } warn(...args) { return log.warn(...args) } info(...args) { return log.info(...args) } verbose(...args) { return log.verbose(...args) } debug(...args) { return log.debug(...args) } setLevel(level) { log.transports.file.level = level; log.transports.console.level = level; } getFile() { return computeLogPath(log.transports.file.fileName) } } export const logger = new Logger(GUI_LOG_FILENAME) logger.setLevel('debug')
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
// @flow import type { Action } from './types'; import produce from 'immer'; import moment from 'moment'; import { ACTION_APP_STATUS_ITEM_ADD, ACTION_APP_STATUS_ITEM_CLEAR, ACTION_APP_STATUS_ITEM_ERROR, ACTION_APP_STATUS_ITEM_SUCCESS } from '../services/statusActions'; const initialState = {items: {}} const reducer = produce((state, action) => { const payload = action.payload switch (action.type) { case ACTION_APP_STATUS_ITEM_ADD: { payload.time = moment().valueOf() state.items[payload.id] = payload return } case ACTION_APP_STATUS_ITEM_SUCCESS: { const statusItem = state.items[payload.id] if (statusItem === undefined) { return } statusItem.success = true return } case ACTION_APP_STATUS_ITEM_ERROR: { const statusItem = state.items[payload.id] if (statusItem === undefined) { return } statusItem.error = true statusItem.errorMessage = payload.errorMessage return } case ACTION_APP_STATUS_ITEM_CLEAR: { delete state.items[payload.id] } default: return } }, initialState) export default reducer
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
// @flow import type { Action } from './types'; import produce from 'immer'; import { POOLS_SET } from '../actions/poolsActions'; const initialState = { /*pools: { pools: [] }*/ } const reducer = produce((state, action) => { const payload = action.payload switch (action.type) { case POOLS_SET: state.pools = payload return default: return } }, initialState) export default reducer
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
// @flow import { combineReducers } from 'redux'; import { connectRouter } from 'connected-react-router'; import cli from './cli'; import gui from './gui'; import wallet from './wallet'; import mix from './mix'; import pools from './pools'; import status from './status'; export default function createRootReducer(history: History) { return combineReducers({ router: connectRouter(history), cli: cli, gui: gui, wallet: wallet, status: status, mix: mix, pools: pools }); }
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
// @flow import { WALLET_SET } from '../actions/walletActions'; import type { Action } from './types'; import produce from 'immer'; const initialState = { /*wallet: { deposit: { utxos:[], balance:0 }, premix: { utxos:[], balance:0 }, postmix: { utxos:[], balance:0 } }*/ } const reducer = produce((state, action) => { const payload = action.payload switch (action.type) { case WALLET_SET: state.wallet = payload return default: return } }, initialState) export default reducer
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
// @flow import type { Action } from './types'; import produce from 'immer'; import { GUI_SET } from '../actions/guiActions'; const initialState = { /*gui: { status: 'NOT_INITIALIZED' }*/ } const reducer = produce((state, action) => { const payload = action.payload switch (action.type) { case GUI_SET: state.gui = payload return default: return } }, initialState) export default reducer
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
// @flow import type { Action } from './types'; import produce from 'immer'; import { MIX_SET } from '../actions/mixActions'; const initialState = { /*mix: { started: false, nbMixing: 0, nbQueued:0, threads: [] }*/ } const reducer = produce((state, action) => { const payload = action.payload switch (action.type) { case MIX_SET: state.mix = payload return default: return } }, initialState) export default reducer
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
// @flow import type { Action } from './types'; import produce from 'immer'; import { CLI_SET } from '../actions/cliActions'; const initialState = { /*cli: { status: 'NOT_INITIALIZED' }*/ } const reducer = produce((state, action) => { const payload = action.payload switch (action.type) { case CLI_SET: state.cli = payload return default: return } }, initialState) export default reducer
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
// @flow import React, { Component } from 'react'; import './PremixPage.css'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import * as Icons from '@fortawesome/free-solid-svg-icons'; import { Dropdown, DropdownButton } from 'react-bootstrap'; import { bindActionCreators } from 'redux'; import { walletActions } from '../actions/walletActions'; import { connect } from 'react-redux'; import walletService from '../services/walletService'; import mixService from '../services/mixService'; import poolsService from '../services/poolsService'; import UtxosTable from '../components/Utxo/UtxosTable'; class LastActivityPage extends Component { constructor(props) { super(props) } // tx0 render() { if (!walletService.isReady()) { return <small>Fetching wallet...</small> } if (!mixService.isReady()) { return <small>Fetching mix state...</small> } if (!poolsService.isReady()) { return <small>Fetching pools...</small> } const utxosDeposit = walletService.getUtxosDeposit().filter(a => a.lastActivityElapsed ? true : false) const utxosPremix = walletService.getUtxosPremix().filter(a => a.lastActivityElapsed ? true : false) const utxosPostmix = walletService.getUtxosPostmix().filter(a => a.lastActivityElapsed ? true : false) let utxos = utxosDeposit.concat(utxosPremix).concat(utxosPostmix).sort((a,b) => a.lastActivityElapsed - b.lastActivityElapsed) return ( <div className='lastActivityPage'> <div className='row'> <div className='col-sm-12'> <h2>Last activity <FontAwesomeIcon icon={Icons.faCircleNotch} spin size='xs' /></h2> </div> </div> <div className='row h-100 d-flex flex-column'> <div className='col-sm-12 flex-grow-1 tablescroll'> <UtxosTable utxos={utxos} controls={false} account={true}/> </div> </div> </div> ); } } function mapStateToProps(state) { return { wallet: state.wallet }; } function mapDispatchToProps (dispatch) { return { dispatch, walletActions: bindActionCreators(walletActions, dispatch) } } export default connect( mapStateToProps, mapDispatchToProps )(LastActivityPage);
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
// @flow import React, { Component } from 'react'; import './PremixPage.css'; import { Dropdown, DropdownButton } from 'react-bootstrap'; import { bindActionCreators } from 'redux'; import { walletActions } from '../actions/walletActions'; import { connect } from 'react-redux'; import walletService from '../services/walletService'; import utils, { WHIRLPOOL_ACCOUNTS } from '../services/utils'; import mixService from '../services/mixService'; import poolsService from '../services/poolsService'; import modalService from '../services/modalService'; import UtxosTable from '../components/Utxo/UtxosTable'; class DepositPage extends Component { constructor(props) { super(props) } // tx0 render() { if (!walletService.isReady()) { return <small>Fetching wallet...</small> } if (!mixService.isReady()) { return <small>Fetching mix state...</small> } if (!poolsService.isReady()) { return <small>Fetching pools...</small> } const utxos = walletService.getUtxosDeposit() return ( <div className='depositPage h-100'> <div className='row'> <div className='col-sm-2'> <h2>Deposit</h2> </div> <div className='col-sm-10 stats'> <a className='zpubLink' href='#' onClick={e => {modalService.openZpub(WHIRLPOOL_ACCOUNTS.DEPOSIT, walletService.getZpubDeposit());e.preventDefault()}}>ZPUB</a> <span className='text-primary'>{utxos.length} utxos ({utils.toBtc(walletService.getBalanceDeposit())}btc)</span> </div> </div> <div className='row h-100 d-flex flex-column'> <div className='col-sm-12 flex-grow-1 tablescroll'> <UtxosTable utxos={utxos} controls={true} account={false}/> </div> </div> </div> ); } } function mapStateToProps(state) { return { wallet: state.wallet }; } function mapDispatchToProps (dispatch) { return { dispatch, walletActions: bindActionCreators(walletActions, dispatch) } } export default connect( mapStateToProps, mapDispatchToProps )(DepositPage);
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
// @flow import React, { Component } from 'react'; import './PremixPage.css'; import walletService from '../services/walletService'; import utils, { WHIRLPOOL_ACCOUNTS } from '../services/utils'; import mixService from '../services/mixService'; import poolsService from '../services/poolsService'; import { Dropdown, DropdownButton } from 'react-bootstrap'; import modalService from '../services/modalService'; import UtxosTable from '../components/Utxo/UtxosTable'; type Props = {}; export default class PremixPage extends Component<Props> { props: Props; render() { if (!walletService.isReady()) { return <small>Fetching wallet...</small> } if (!mixService.isReady()) { return <small>Fetching mix state...</small> } if (!poolsService.isReady()) { return <small>Fetching pools...</small> } const utxos = walletService.getUtxosPremix() return ( <div className='premixPage h-100'> <div className='row'> <div className='col-sm-2'> <h2>Premix</h2> </div> <div className='col-sm-10 stats'> <a className='zpubLink' href='#' onClick={e => {modalService.openZpub(WHIRLPOOL_ACCOUNTS.PREMIX, walletService.getZpubPremix());e.preventDefault()}}>ZPUB</a> <span className='text-primary'>{utxos.length} utxos ({utils.toBtc(walletService.getBalancePremix())}btc)</span> </div> </div> <div className='row h-100 d-flex flex-column'> <div className='col-sm-12 flex-grow-1 tablescroll'> <UtxosTable utxos={utxos} controls={true} account={false}/> </div> </div> </div> ); } }
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
// @flow import React, { Component } from 'react'; import './PremixPage.css'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { Dropdown, DropdownButton } from 'react-bootstrap'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import poolsService from '../services/poolsService'; import utils from '../services/utils'; class PoolsPage extends Component { constructor(props) { super(props) } render() { if (!poolsService.isReady()) { return <small>Fetching pools...</small> } return ( <div className='poolsPage'> <div className='row'> <div className='col-sm-12'> <h2>Pools</h2> </div> </div> <table className='pools table text-center'> <thead> <tr> <th>Name</th> <th>Denomination</th> <th>Min. deposit</th> <th>Max. deposit</th> <th>Max. mixs</th> <th>Anonymity set per mix</th> <th>Whirlpool fee</th> </tr> </thead> <tbody> {poolsService.getPools().map((pool,i) => <tr key={i}> <td>{pool.poolId}</td> <td>{utils.toBtc(pool.denomination)}</td> <td>{utils.toBtc(pool.tx0BalanceMin)}</td> <td>∞</td> <td>∞</td> <td>{pool.mixAnonymitySet}</td> <td>{utils.toBtc(pool.feeValue)}</td> </tr>)} </tbody> </table> </div> ); } } function mapStateToProps(state) { return { }; } function mapDispatchToProps (dispatch) { return { dispatch, } } export default connect( mapStateToProps, mapDispatchToProps )(PoolsPage);
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
// @flow import * as React from 'react'; import { Route, Switch, withRouter } from 'react-router'; import backendService from '../services/backendService'; import { connect } from 'react-redux'; import { Helmet } from 'react-helmet'; import walletService from '../services/walletService'; import { bindActionCreators } from 'redux'; import { cliActions } from '../actions/cliActions'; import { guiActions } from '../actions/guiActions'; import { walletActions } from '../actions/walletActions'; import { poolsActions } from '../actions/poolsActions'; import { mixActions } from '../actions/mixActions'; import { Link } from 'react-router-dom'; import * as Icon from 'react-feather'; import routes from '../constants/routes'; import ConfigPage from '../containers/ConfigPage'; import InitPage from '../containers/InitPage'; import PremixPage from './PremixPage'; import DepositPage from '../containers/DepositPage'; import LastActivityPage from './LastActivityPage'; import Status from '../components/Status'; import { statusActions } from '../services/statusActions'; import PostmixPage from './PostmixPage'; import utils from '../services/utils'; import MixStatus from '../components/MixStatus'; import mixService from '../services/mixService'; import modalService from '../services/modalService'; import Tx0Modal from '../components/Modals/Tx0Modal'; import DepositModal from '../components/Modals/DepositModal'; import ZpubModal from '../components/Modals/ZpubModal'; import poolsService from '../services/poolsService'; import cliService from '../services/cliService'; import ConnectingPage from './ConnectingPage'; import StatusPage from './StatusPage'; import LoginPage from './LoginPage'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { cliLocalService } from '../services/cliLocalService'; import { cliApiService, GUI_VERSION } from '../const'; import * as Icons from '@fortawesome/free-solid-svg-icons'; import PoolsPage from './PoolsPage'; import guiUpdateService from '../services/guiUpdateService'; import { Alert } from 'react-bootstrap'; type Props = { children: React.Node }; class App extends React.Component<Props> { props: Props; constructor(props) { super(props) this.state = { // managed by modalService } // init services backendService.init(props.dispatch) cliService.init(props.cli, cliState => props.cliActions.set(cliState) ) guiUpdateService.init(props.gui, guiState => props.guiActions.set(guiState) ) mixService.init(props.mix, mixState => props.mixActions.set(mixState) ) walletService.init(props.wallet, walletState => props.walletActions.set(walletState) ) poolsService.init(props.pools, poolsState => props.poolsActions.set(poolsState) ) modalService.init(this.setState.bind(this)) // start cli cliService.start() } routes() { if (cliService.isLoggedIn()) { // logged in return <Switch> <Route path={routes.STATUS} component={StatusPage}/> <Route path={routes.DEPOSIT} component={DepositPage}/> <Route path={routes.PREMIX} component={PremixPage}/> <Route path={routes.POSTMIX} component={PostmixPage}/> <Route path={routes.POOLS} component={PoolsPage}/> <Route path={routes.CONFIG} component={ConfigPage}/> <Route path={routes.HOME} component={LastActivityPage}/> </Switch> } if (!cliService.isConfigured() || cliService.isCliStatusNotInitialized()) { // not configured/initialized return <Switch> <Route path={routes.STATUS} component={StatusPage}/> <Route path={routes.HOME} component={InitPage} /> </Switch> } if (!cliService.isCliStatusReady()) { // not connected return <Switch> <Route path={routes.STATUS} component={StatusPage}/> <Route path={routes.HOME} component={ConnectingPage} /> </Switch> } if (!cliService.isLoggedIn()) { return <Switch> <Route path={routes.STATUS} component={StatusPage}/> <Route path={routes.CONFIG} component={ConfigPage}/> <Route path={routes.HOME} component={LoginPage}/> </Switch> } } render() { const cliLocalStatusIcon = cliService.isCliLocal() ? cliLocalService.getStatusIcon((icon,text)=>icon) : undefined const cliStatusIcon = cliService.getStatusIcon((icon,text)=>icon) const loginLogoutIcon = cliService.getLoginStatusIcon((icon,text)=>icon) const cliInfo = cliService.isCliLocal() ? 'CLI '+cliLocalService.getCliVersionStr():'CLI_API '+cliApiService.getVersionName() const torIcon = cliService.isConnected() && cliService.getTorProgressIcon() ? <span className='icon'>{cliService.getTorProgressIcon()}</span> : undefined const dojoIcon = cliService.isConnected() && cliService.getDojoIcon() ? <span className='icon'>{cliService.getDojoIcon()}</span> : undefined const guiUpdate = guiUpdateService.getGuiUpdate() return <div className='h-100'> <Helmet> <title>Whirlpool - Samourai Wallet - GUI {GUI_VERSION}, {cliInfo}</title> </Helmet> <nav className="navbar navbar-dark fixed-top bg-dark flex-md-nowrap p-0 shadow"> <div className='col-sm-3 col-md-2 mr-0 navbar-brand-col'> <div className="branding"> <a href='#' className="brand-logo"> <span className="logo icon-samourai-logo-trans svglogo"></span> </a> <a href='#' className='product-title'>Whirlpool</a> </div> {cliStatusIcon && <div className='cliStatus'> <span className='icon'>{cliStatusIcon}</span> {dojoIcon} {torIcon} <span className='icon'>{loginLogoutIcon}</span> </div>} </div> <div className='col-md-10'> {cliService.isLoggedIn() && (mixService.isReady() && poolsService.isReady() ? <MixStatus mixState={this.props.mix} poolsState={this.props.pools} mixActions={this.props.mixActions}/> : <small>Fetching mix state...</small>)} {cliService.isCliStatusReady() && !cliService.isLoggedIn() && <div className='text-center'> <Link to={routes.HOME}> <FontAwesomeIcon icon={Icons.faLock} size='3x' color='#CCC'/> </Link> </div>} {(!cliService.isConfigured() || cliService.isCliStatusNotInitialized()) && <div className='text-center'> <Link to={routes.HOME}> <FontAwesomeIcon icon={Icons.faCogs} size='3x' color='#CCC'/> </Link> </div>} </div> </nav> <div className="container-fluid h-100 main-container"> <div className="row h-100"> <nav className="col-md-2 d-none d-md-block bg-light sidebar"> <div className="sidebar-sticky"> {cliService.isLoggedIn() && walletService.isReady() && <div> <button className='btn btn-sm btn-primary btn-deposit' onClick={() => modalService.openDeposit()}><Icon.Plus size={12}/> Deposit</button> <div><small>Balance: {utils.toBtc(walletService.getBalanceDeposit()+walletService.getBalancePremix()+walletService.getBalancePostmix(), true)}</small></div> </div>} <ul className="nav flex-column"> {cliService.isCliStatusReady() && !cliService.isLoggedIn() && <li className="nav-item"> <Link to={routes.HOME} className="nav-link"> <span data-feather="terminal"></span> <strong>Authentication</strong> </Link> </li>} {cliService.isLoggedIn() && walletService.isReady() && <li className="nav-item"> <Link to={routes.LAST_ACTIVITY} className="nav-link"> <span data-feather="terminal"></span> Last activity </Link> </li>} {cliService.isLoggedIn() && walletService.isReady() && <li className="nav-item"> <Link to={routes.DEPOSIT} className="nav-link"> <span data-feather="plus"></span> Deposit ({walletService.getUtxosDeposit().length} · {utils.toBtc(walletService.getBalanceDeposit(), true)}) </Link> </li>} {cliService.isLoggedIn() && walletService.isReady() && <li className="nav-item"> <Link to={routes.PREMIX} className="nav-link"> <span data-feather="play"></span> Premix ({walletService.getUtxosPremix().length} · {utils.toBtc(walletService.getBalancePremix(), true)}) </Link> </li>} {cliService.isLoggedIn() && walletService.isReady() && <li className="nav-item"> <Link to={routes.POSTMIX} className="nav-link"> <span data-feather="check"></span> Postmix ({walletService.getUtxosPostmix().length} · {utils.toBtc(walletService.getBalancePostmix(), true)}) </Link> </li>} {cliService.isLoggedIn() && walletService.isReady() && <br/>} {cliService.isLoggedIn() && walletService.isReady() && <li className="nav-item"> <Link to={routes.POOLS} className="nav-link"> <span data-feather="check"></span> Pools </Link> </li>} {cliService.isConfigured() && cliService.isCliStatusReady() && <li className="nav-item"> <Link to={routes.CONFIG} className="nav-link"> <span data-feather="settings"></span> Configuration </Link> </li>} {(!cliService.isConfigured() || cliService.isCliStatusNotInitialized()) && <li className="nav-item"> <Link to={routes.HOME} className="nav-link"> <span data-feather="settings"></span> <strong>Setup</strong> </Link> </li>} <li className="nav-item"> <Link to={routes.STATUS} className="nav-link"> <span data-feather="terminal"></span> System </Link> </li> </ul> {cliService.isLoggedIn() && !walletService.isReady() && <div> <small>Fetching wallet...</small> </div>} <div className="footerNav"> <div> {cliService.isConnected() && <small>{cliService.getServerName()}</small>} {cliService.isCliLocal() && <small> {cliLocalStatusIcon} standalone</small>} </div> {!cliService.isCliLocal() && <div><small>{cliService.getCliUrl()}</small></div>} </div> </div> <Status status={this.props.status} statusActions={this.props.statusActions} /> </nav> <main role="main" className="col-md-10 ml-sm-auto col-lg-10 px-4"> {guiUpdate && <div><br/><Alert variant='warning'>GUI update {guiUpdate} available!</Alert></div>} {this.routes()} {this.state.modalTx0 && <Tx0Modal utxo={this.state.modalTx0} onClose={modalService.close.bind(modalService)}/>} {this.state.modalDeposit && <DepositModal onClose={modalService.close.bind(modalService)}/>} {this.state.modalZpub && <ZpubModal zpub={this.state.modalZpub.zpub} account={this.state.modalZpub.account} onClose={modalService.close.bind(modalService)}/>} </main> </div> </div> </div> } } function mapStateToProps(state) { return { status: state.status, cli: state.cli, gui: state.gui, wallet: state.wallet, mix: state.mix, pools: state.pools }; } function mapDispatchToProps (dispatch) { return { dispatch, statusActions: bindActionCreators(statusActions, dispatch), cliActions: bindActionCreators(cliActions, dispatch), guiActions: bindActionCreators(guiActions, dispatch), walletActions: bindActionCreators(walletActions, dispatch), poolsActions: bindActionCreators(poolsActions, dispatch), mixActions: bindActionCreators(mixActions, dispatch) } } export default withRouter(connect( mapStateToProps, mapDispatchToProps )(App));
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
// @flow import React, { Component } from 'react'; import { Alert, Card } from 'react-bootstrap'; import { connect } from 'react-redux'; import { ipcRenderer } from 'electron'; import * as Icons from '@fortawesome/free-solid-svg-icons'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import WebcamPayloadModal from '../components/Modals/WebcamPayloadModal'; import cliService from '../services/cliService'; import { DEFAULT_CLIPORT, IPC_CAMERA } from '../const'; import { cliLocalService } from '../services/cliLocalService'; import utils from '../services/utils'; import guiConfig from '../mainProcess/guiConfig'; const STEP_LAST = 3 const DEFAULT_CLIHOSTPORT = 'https://myRemoteCLI:'+DEFAULT_CLIPORT const DEFAULT_APIKEY = '' const DEFAUT_GUI_PROXY = 'socks5://127.0.0.1:9050' const CLILOCAL_URL = 'https://localhost:'+DEFAULT_CLIPORT class InitPage extends Component<Props> { props: Props; constructor(props) { super(props) this.state = { step: 0, navNextStep: false, cliLocal: cliService.isCliLocal(), cliUrl: undefined, currentCliHostPort: DEFAULT_CLIHOSTPORT, currentApiKey: DEFAULT_APIKEY, showGuiProxy: false, showApiKey: false, cliError: undefined, hasPairingPayload: false, hasPairingDojo: false, dojo: false, tor: false, pairingPayload: '', pairingError: undefined, cliInitError: undefined, cameraError: null, pairingModal: false, cameraAccessGranted: false, } // configuration data this.hasPairingPayload = undefined this.inputCliHostPort = React.createRef() this.inputApiKey = React.createRef() this.goNextStep = this.goNextStep.bind(this) this.goPrevStep = this.goPrevStep.bind(this) this.onChangeCliLocal = this.onChangeCliLocal.bind(this) this.onChangeInputCliHostPort = this.onChangeInputCliHostPort.bind(this) this.connectCli = this.connectCli.bind(this) this.onChangePairingPayload = this.onChangePairingPayload.bind(this) this.onChangeTor = this.onChangeTor.bind(this) this.onChangeDojo = this.onChangeDojo.bind(this) this.onChangeGuiProxy = this.onChangeGuiProxy.bind(this) this.onSubmitInitialize = this.onSubmitInitialize.bind(this) } componentDidMount() { ipcRenderer.on(IPC_CAMERA.GRANTED, () => { this.setState({ cameraAccessGranted: true }) }); ipcRenderer.on(IPC_CAMERA.DENIED, () => { this.setState({ cameraAccessGranted: false, pairingModal: false, cameraError: "Camera access was denied or is unavailable." }) }); } openPairingModal = () => { ipcRenderer.send(IPC_CAMERA.REQUEST); this.setState({ pairingModal: true }); }; closePairingModal = () => { this.setState({ pairingModal: false }); }; goNextStep () { this.goStep(this.state.step+1) } goPrevStep () { this.goStep(this.state.step-1) } goStep (i) { this.setState({step: i}) } navButtons(next=true,previous=true) { this.navNextStep = next return <div className="form-group row"> <div className="col-sm-5"> {previous && this.state.step > 0 && <button type="button" className="btn btn-default" onClick={this.goPrevStep}><FontAwesomeIcon icon={Icons.faArrowLeft} /></button>} </div> <div className="col-sm-5"> {next && <button type="submit" className="btn btn-primary"> Continue <FontAwesomeIcon icon={Icons.faArrowRight} /></button>} </div> </div> } render() { return ( <div> <h1>Whirlpool setup</h1> <p>This will connect Whirlpool to Samourai Wallet.</p> {this.state.cliUrl && <div><FontAwesomeIcon icon={Icons.faCheck} color='green' /> Connected to whirlpool-cli: <strong>{this.state.cliLocal ? 'standalone' : this.state.cliUrl}</strong></div>} {this.state.hasPairingPayload && <div><FontAwesomeIcon icon={Icons.faCheck} color='green' /> Ready to pair with Samourai Wallet</div>} {this.state.step === STEP_LAST && <div><FontAwesomeIcon icon={Icons.faCheck} color='green' /> Configuration saved</div>} <br/> <form onSubmit={(e) => { if (this.navNextStep) { this.goNextStep(); } e.preventDefault() }}> {this.state.step === 0 && this.step0()} {this.state.step === 1 && this.step1()} {this.state.step === 2 && this.step2()} {this.state.step === STEP_LAST && this.step3()} </form> {this.state.pairingModal && this.state.cameraAccessGranted && ( <WebcamPayloadModal onClose={this.closePairingModal} onScan={(value) => this.onChangePairingPayload(value)} /> )} </div> ); } // cli instance selection onChangeCliLocal(e) { const valueBool = e.target.value === 'true' cliService.setCliLocal(valueBool) this.setState({ cliLocal: valueBool }); this.resetCliUrl() } resetCliUrl(resetToggles=true) { const newState = { cliUrl: undefined, cliError: undefined, currentCliHostPort: DEFAULT_CLIHOSTPORT, currentApiKey: DEFAULT_APIKEY } if (resetToggles) { newState.showApiKey = false newState.showGuiProxy = false } this.setState(newState); this.resetPairingPayload() } onChangeInputCliHostPort(e) { this.resetCliUrl(false) const cliHostPort = this.inputCliHostPort.current ? this.inputCliHostPort.current.value : undefined const apiKey = this.inputApiKey.current ? this.inputApiKey.current.value : undefined const newState = { currentCliHostPort: cliHostPort, currentApiKey: apiKey } const showGuiProxy = cliHostPort && cliHostPort.indexOf('.onion')!==-1 if (showGuiProxy) { newState.showGuiProxy = showGuiProxy if (!guiConfig.getGuiProxy()) { // set default GUI proxy guiConfig.setGuiProxy(DEFAUT_GUI_PROXY) } } this.setState(newState) } computeCliUrl() { const cliUrl = (this.state.cliLocal ? CLILOCAL_URL:this.state.currentCliHostPort) return cliUrl } connectCli() { const cliUrl = this.computeCliUrl() const apiKey = this.state.currentApiKey const cliLocal = this.state.cliLocal cliService.testCliUrl(cliUrl, apiKey).then(cliStatusReady => { // connection success this.setState({ cliUrl: cliUrl, cliError: undefined }) if (cliStatusReady) { // CLI already initialized => save configuration & finish cliService.saveConfig(cliUrl, apiKey, cliLocal) this.goStep(STEP_LAST) } else { // CLI not initialized yet => continue configuration this.goNextStep() } }).catch(error => { if (error && error.message.indexOf('API Key')) { this.setState({showApiKey:true}) } console.error('testCliUrl failed',error) this.setState({ cliError: error.message }) }) } step0() { return <div> <div className="form-group row"> <div className="col-sm-12"> How do you want to use this GUI? </div> </div> <div className="form-group row"> <label htmlFor="inputEmail3" className="col-sm-1 col-form-label"></label> <div className="col-sm-11"> <div className="form-check"> <input className="form-check-input" type="radio" name="cliLocal" id="cliLocalTrue" value='true' checked={this.state.cliLocal} onChange={this.onChangeCliLocal}/> <label className="form-check-label" htmlFor="cliLocalTrue"> <strong>Standard: standalone GUI</strong> </label> </div> <div className="form-check"> <input className="form-check-input" type="radio" name="cliLocal" id="cliLocalFalse" value='false' checked={!this.state.cliLocal} onChange={this.onChangeCliLocal} /> <label className="form-check-label" htmlFor="cliLocalFalse"> <strong>Advanced: remote CLI</strong> </label> </div> </div> </div> {this.state.cliLocal && <div> <div className="row"> <div className="col-sm-1"></div> {cliLocalService.getStatusIcon((icon,text)=><div className='col-sm-8'><Alert variant='success'>{icon} {text}</Alert></div>)} {!cliLocalService.isStatusDownloading() && !cliLocalService.isValid() && <div className='col-sm-12'><Alert variant='danger'>No valid CLI found. Please reinstall GUI.</Alert></div>} </div> {cliLocalService.isValid() && <div className="row"> <div className="col-sm-3"></div> <button type="button" className="btn btn-primary col-sm-3" onClick={this.connectCli}> Continue <FontAwesomeIcon icon={Icons.faArrowRight} /></button> </div>} </div>} {!this.state.cliLocal && <Card> <Card.Header>Remote CLI</Card.Header> <Card.Body> <div className="form-group row"> <div className="col-sm-11"> <div className="row"> <label htmlFor="cliHostPort" className="col-sm-2 col-form-label">CLI address</label> <input type="text" id="cliHostPort" className="form-control col-sm-4" placeholder={DEFAULT_CLIHOSTPORT} defaultValue={this.state.currentCliHostPort} ref={this.inputCliHostPort} onChange={this.onChangeInputCliHostPort} required/> &nbsp; {this.state.currentCliHostPort && !this.state.cliUrl && <button type='button' className='btn btn-primary col-sm-2' onClick={this.connectCli}>Connect</button>} </div> &nbsp; {this.state.showGuiProxy && <div className="row"> <label htmlFor="guiProxy" className="col-sm-2 col-form-label">Tor proxy</label> <input type="text" id="guiProxy" className="form-control col-sm-4" defaultValue={guiConfig.getGuiProxy()} onChange={this.onChangeGuiProxy}/> <label className='col-form-label col-sm-6 text-muted'> Only required when CLI behind a Hidden Service.<br/> <code>{DEFAUT_GUI_PROXY}</code> </label> </div>} {this.state.showApiKey && <div className="row"> <label htmlFor="apiKey" className="col-sm-2 col-form-label">API Key</label> <input type="password" id="apiKey" className="form-control col-sm-4" defaultValue={this.state.currentApiKey} ref={this.inputApiKey} onChange={this.onChangeInputCliHostPort} /> <label className='col-form-label col-sm-6 text-muted'> Only required when CLI already initialized<br/>(<code>cli.apiKey</code> in <code>whirlpool-cli-config.properties</code>) </label> </div>} <div className="row"> <div className="col-sm-1"></div> {!this.state.showGuiProxy && <div className="col-sm-3 col-form-label"> <a onClick={() => this.setState({showGuiProxy:true})}>Use a Tor proxy?</a> </div>} {!this.state.showApiKey && <div className="col-sm-3 col-form-label"> <a onClick={() => this.setState({showApiKey:true})}>Configure API key?</a> </div>} </div> </div> </div> </Card.Body> </Card> } {this.state.cliError && <div className="row"> <div className="col-sm-12"><br/> <Alert variant='danger'>Connection failed: {this.state.cliError}</Alert> </div> </div>} {this.navButtons(false)} </div> } // pairing resetPairingPayload() { this.setState({ pairingPayload: '', hasPairingPayload: false, pairingError: undefined, cliInitError: undefined }) } onChangePairingPayload(payloadStr) { this.setState({ pairingPayload: payloadStr }); let payload = undefined try { payload = JSON.parse(payloadStr) } catch(e) {} if (payload && payload.pairing && Object.keys(payload.pairing).length > 0) { const isDojo = payload.dojo && Object.keys(payload.dojo).length > 0 // seems valid this.setState({ hasPairingPayload: true, hasPairingDojo: isDojo, dojo: isDojo, tor: isDojo, pairingError: undefined }) this.goNextStep() } else { // invalid payload console.error('Invalid payload: '+payloadStr) this.setState({ hasPairingPayload: false, hasPairingDojo: false, dojo: false, tor: false, pairingError: 'Invalid payload' }) } } onChangeTor(tor) { this.setState({ tor: tor }) } onChangeDojo(value) { this.setState({ dojo: value }) } onChangeGuiProxy(e) { const value = e.target.value guiConfig.setGuiProxy(value) } onSubmitInitialize() { cliService.initializeCli(this.state.cliUrl, this.state.currentApiKey, this.state.cliLocal, this.state.pairingPayload, this.state.tor, this.state.dojo).then(() => { // success! this.goNextStep() }).catch(error => { console.error('initialization failed', error) this.setState({ cliInitError: error.message }) }) } step1() { return <div> <div className="form-group row"> <div className="col-sm-1 text-right"> <FontAwesomeIcon icon={Icons.faMobileAlt} size='6x'/> </div> <div className="col-sm-11"> <div className="row"> <div className="col-sm-12"> Get your <strong>pairing payload</strong> from Samourai Wallet, go to <strong>Settings/Transactions/Experimental</strong> then{' '} <a onClick={(event) => { event.preventDefault(); this.openPairingModal(); }} href="#"><strong>scan it using webcam</strong></a>.<br/> <br/> <div className="row"> <div className="col-sm-10"> <input type="text" className='form-control form-control-lg' required autoFocus onChange={e => { this.onChangePairingPayload(e.target.value) }} onClick={e => { e.target.value = '' this.resetPairingPayload() }} value={this.state.pairingPayload} id="pairingPayload" placeholder='Scan or paste your pairing payload here'/> </div> <div className="col-sm-2 text-left"> <a title="Scan your pairing payload using webcam" onClick={(event) => { event.preventDefault(); this.openPairingModal(); }} href="#"><FontAwesomeIcon icon={Icons.faQrcode} size='3x'/></a> </div> </div> </div> </div> {this.state.pairingError && <div className="col-sm-12"><br/> <Alert variant='danger'>{this.state.pairingError}</Alert> </div>} {this.state.cameraError && <div className="col-sm-12"><br/> <Alert variant='danger'>{this.state.cameraError}</Alert> </div>} </div> </div> {this.navButtons(this.state.pairingPayload)} </div> } step2() { const checked = e => { return e.target.checked } const myThis = this return <div> <div className="row"> <div className="col-sm-1 text-center"> {utils.torIcon('100%')} </div> <div className="col-sm-4"> {this.state.hasPairingDojo && <div> <div className='custom-control custom-switch'> <input type="checkbox" className="custom-control-input" onChange={e => myThis.onChangeDojo(checked(e))} defaultChecked={myThis.state.dojo} id="dojo"/> <label className="custom-control-label" htmlFor="dojo">Use Dojo as wallet backend <FontAwesomeIcon icon={Icons.faHdd}/></label> </div> {this.state.dojo && <div> <div className='custom-control custom-switch'> <input type="checkbox" className="custom-control-input" defaultChecked={true} id="torDojo" disabled/> <label className="custom-control-label" htmlFor="torDojo">Tor is required for Dojo</label> </div> </div>} </div>} {!this.state.dojo && <div className='custom-control custom-switch'> <input type="checkbox" className="custom-control-input" onChange={e => myThis.onChangeTor(checked(e))} defaultChecked={myThis.state.tor} id="tor"/> <label className="custom-control-label" htmlFor="tor">Enable Tor</label> </div>} </div> <div className="col-sm-7"> <button type="button" className="btn btn-primary btn-lg" onClick={this.onSubmitInitialize}>Initialize GUI</button> </div> </div> {this.state.cliInitError && <div className="row"> <div className="col-sm-12"> <Alert variant='danger'>Initialization failed: {this.state.cliInitError}</Alert> </div> </div>} {this.navButtons(false)} </div> } step3() { return <div> <p>Success. <b>whirlpool-gui</b> is now configured.</p> <p>Reconnecting to CLI...</p> </div> } } function mapStateToProps(state) { return { }; } function mapDispatchToProps (dispatch) { return { dispatch } } export default connect( mapStateToProps, mapDispatchToProps )(InitPage);
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
// @flow import React, { Component } from 'react'; import { connect } from 'react-redux'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import cliService from '../services/cliService'; import { Alert } from 'react-bootstrap'; import * as Icons from "@fortawesome/free-solid-svg-icons"; import utils from '../services/utils'; class LoginPage extends Component<Props> { props: Props; constructor(props) { super(props) this.state = { loginError: undefined } this.inputPassphrase = React.createRef() this.onSubmit = this.onSubmit.bind(this) } onSubmit() { this.setState({ loginError: undefined }) const seedPassphrase = this.inputPassphrase.current.value cliService.login(seedPassphrase).catch(e => this.setState({ loginError: e.message })) } render() { return ( <form className="form-signin text-center" onSubmit={(e) => {this.onSubmit();e.preventDefault()}}> <h1 className="h3 mb-3 font-weight-normal">Authentication</h1> <div><FontAwesomeIcon icon={Icons.faLock} size='3x' color='#343a40'/></div><br/> <p>Your passphrase is required<br/>for opening wallet.</p> <input type="password" id="seedPassphrase" className="form-control" placeholder="Wallet passphrase" ref={this.inputPassphrase} required autoFocus/> <button className="btn btn-lg btn-primary btn-block" type="submit">Sign in</button> <br/> {cliService.isTor() && <div> {utils.torIcon()} Please be patient signing in with Tor<br/><br/></div>} {this.state.loginError && <Alert variant='danger'>Authentication failed: {this.state.loginError}</Alert>} </form> ) } } function mapStateToProps(state) { return { }; } function mapDispatchToProps (dispatch) { return { dispatch } } export default connect( mapStateToProps, mapDispatchToProps )(LoginPage);
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
// @flow import React, { Component } from 'react'; import './PostmixPage.css'; import walletService from '../services/walletService'; import utils, { WHIRLPOOL_ACCOUNTS } from '../services/utils'; import mixService from '../services/mixService'; import modalService from '../services/modalService'; import poolsService from '../services/poolsService'; import { Dropdown, DropdownButton } from 'react-bootstrap'; import UtxosTable from '../components/Utxo/UtxosTable'; type Props = {}; export default class PostmixPage extends Component<Props> { props: Props; render() { if (!walletService.isReady()) { return <small>Fetching wallet...</small> } if (!mixService.isReady()) { return <small>Fetching mix state...</small> } if (!poolsService.isReady()) { return <small>Fetching pools...</small> } const utxos = walletService.getUtxosPostmix() return ( <div className='postmixPage h-100'> <div className='row'> <div className='col-sm-2'> <h2>Postmix</h2> </div> <div className='col-sm-10 stats'> <a className='zpubLink' href='#' onClick={e => {modalService.openZpub(WHIRLPOOL_ACCOUNTS.POSTMIX, walletService.getZpubPostmix());e.preventDefault()}}>ZPUB</a> <span className='text-primary'>{utxos.length} utxos ({utils.toBtc(walletService.getBalancePostmix())}btc)</span> </div> </div> <div className='row h-100 d-flex flex-column'> <div className='col-sm-12 flex-grow-1 tablescroll'> <UtxosTable utxos={utxos} controls={true} account={false}/> </div> </div> </div> ); } }
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
// @flow import React, { Component } from 'react'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { cliLocalService } from '../services/cliLocalService'; import cliService from '../services/cliService'; import { APP_USERDATA, CLI_CONFIG_FILENAME, CLI_LOG_ERROR_FILE, CLI_LOG_FILE, cliApiService, GUI_CONFIG_FILENAME, GUI_LOG_FILE, GUI_VERSION } from '../const'; import * as Icons from '@fortawesome/free-solid-svg-icons'; import LinkExternal from '../components/Utils/LinkExternal'; import { Card } from 'react-bootstrap'; import utils from '../services/utils'; import guiConfig from '../mainProcess/guiConfig'; type Props = {}; export default class StatusPage extends Component<Props> { constructor(props) { super(props) this.onResetConfig = this.onResetConfig.bind(this) this.cliLogFile = CLI_LOG_FILE this.cliLogErrorFile = CLI_LOG_ERROR_FILE this.guiLogFile = GUI_LOG_FILE } onResetConfig() { if (confirm('This will reset '+cliService.getResetLabel()+'. Are you sure?')) { cliService.resetConfig() } } render() { const cliStatusIcon = cliService.getStatusIcon((icon,text)=><div>{icon} {text}</div>) return ( <div> <h1>System</h1> <div className='row'> <div className='col-sm-12'> <Card> <Card.Header> <div className='row'> <div className='col-sm-12'> <strong>GUI</strong> </div> </div> </Card.Header> <Card.Body> <div style={{'float':'right'}}> <button type='button' className='btn btn-danger' onClick={this.onResetConfig}><FontAwesomeIcon icon={Icons.faExclamationTriangle} /> Reset {cliService.getResetLabel()}</button> </div> <div className='row'> <div className='col-sm-2'> <strong>Version:</strong> </div> <div className='col-sm-10'> <div>GUI <strong>{GUI_VERSION}</strong>, API <strong>{cliApiService.getVersionName()}</strong></div> </div> </div> {cliService.isConfigured() && <div className='row'> <div className='col-sm-2'> <strong>Mode:</strong> </div> <div className='col-sm-10'> <div><strong>{cliService.isCliLocal()?'Standalone':'Remote CLI'}</strong></div> </div> </div>} {cliService.isConfigured() && !cliService.isCliLocal() && <div className='row'> <div className='col-sm-2'> <strong>GUI proxy:</strong> </div> <div className='col-sm-10'> <div><strong>{guiConfig.getGuiProxy()||'None'}</strong></div> </div> </div>} <div className='row small'> <div className='col-sm-12'> <hr/> </div> </div> <div className='row small'> <div className='col-sm-2'> <strong>Path:</strong><br/> <strong>Config:</strong><br/> <strong>Logs:</strong> </div> <div className='col-sm-10'> <div><LinkExternal href={'file://'+APP_USERDATA}>{APP_USERDATA}</LinkExternal></div> <div></div><LinkExternal href={'file://'+APP_USERDATA+'/'+GUI_CONFIG_FILENAME}>{APP_USERDATA+'/'+GUI_CONFIG_FILENAME}</LinkExternal><br/> <div><LinkExternal href={'file://'+this.guiLogFile}>{this.guiLogFile}</LinkExternal></div> </div> </div> </Card.Body> </Card> <br/> </div> </div> <Card> <Card.Header> <div className='row'> <div className='col-sm-6'> <strong>CLI</strong> </div> </div> </Card.Header> <Card.Body> <div className='row'> <div className='col-sm-2'> <strong>Status:</strong> </div> <div className='col-sm-10'> {cliStatusIcon} </div> </div> {cliService.isConfigured() && !cliService.isCliLocal() && <div> <div className='row'> <div className='col-sm-2'> <strong>Remote CLI:</strong> </div> <div className='col-sm-10'> {cliService.getCliUrl()} </div> </div> </div>} {cliService.isCliLocal() && <div> <div className='row'> <div className='col-sm-2'> <strong>Local CLI:</strong> </div> <div className='col-sm-10'> {cliLocalService.getStatusIcon((icon,text)=><div>{icon} {text}</div>)} </div> </div> <div className='row'> <div className='col-sm-2'> {cliLocalService.hasCliApi() && <strong>JAR:<br/></strong>} {cliLocalService.hasCliApi() && <strong>Version:<br/></strong>} </div> <div className='col-sm-10'> {cliLocalService.hasCliApi() && <div>{cliLocalService.getCliFilename()} ({cliLocalService.getCliChecksum()})</div>} {cliLocalService.hasCliApi() && <div>{cliLocalService.getCliVersionStr()}</div>} {!cliLocalService.hasCliApi() && <div><strong>CLI_API {cliApiService.getVersionName()} could not be resolved</strong><br/></div>} </div> </div> </div>} {cliService.isConfigured() && cliService.isConnected() && <div> <hr/> <div className='row'> <div className='col-sm-2'> <strong>Whirlpool server:</strong><br/> <strong>DOJO:</strong><br/> <strong>Tor:</strong><br/> </div> <div className='col-sm-10'> <div>{cliService.getServerName()}</div> <div> {utils.checkedIcon(cliService.isDojo())} <strong>{cliService.isDojo()?'enabled':'disabled'}</strong>&nbsp; {cliService.isDojo() && <small>{cliService.getDojoUrl()}</small>} </div> <div>{utils.checkedIcon(cliService.isTor())} <strong>{cliService.isTor()?'enabled':'disabled'}</strong></div> </div> </div> </div>} {cliService.isCliLocal() && <div> <hr/> <div className='row small'> <div className='col-sm-2'> <strong>Path:</strong><br/> <strong>Config:</strong><br/> <strong>Logs:</strong><br/> <strong>Errors:</strong> </div> <div className='col-sm-10'> <LinkExternal href={'file://'+cliApiService.getCliPath()}>{cliApiService.getCliPath()}</LinkExternal><br/> <LinkExternal href={'file://'+cliApiService.getCliPath()+CLI_CONFIG_FILENAME}>{cliApiService.getCliPath()+CLI_CONFIG_FILENAME}</LinkExternal><br/> <LinkExternal href={'file://'+this.cliLogFile}>{this.cliLogFile}</LinkExternal><br/> <LinkExternal href={'file://'+this.cliLogErrorFile}>{this.cliLogErrorFile}</LinkExternal> </div> </div> </div>} </Card.Body> </Card> <br/> <br/><br/> </div> ); } }
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
// @flow import React, { Component } from 'react'; import { connect } from 'react-redux'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import cliService from '../services/cliService'; import { Alert } from 'react-bootstrap'; import * as Icons from '@fortawesome/free-solid-svg-icons'; import { cliLocalService } from '../services/cliLocalService'; class ConnectingPage extends Component<Props> { props: Props; constructor(props) { super(props) this.reconnect = this.reconnect.bind(this) this.onResetConfig = this.onResetConfig.bind(this) } render() { const cliUrlError = cliService.getCliUrlError() // or undefined return this.renderConnecting(cliUrlError) } // connecting reconnect() { cliService.fetchState() } renderConnecting(cliUrlError) { return ( <form className="form-signin text-center" onSubmit={(e) => {this.onSubmit();e.preventDefault()}}> <h1 className="h3 mb-3 font-weight-normal">Connecting...</h1> <div><FontAwesomeIcon icon={Icons.faCloud} size='3x' color='#343a40'/></div><br/> <p>Connecting to whirlpool-cli<br/> <strong>{cliService.getCliUrl()}</strong></p> {cliService.isCliLocal() && <div>{cliLocalService.getStatusIcon((icon,text)=><span>{icon} {text}<br/>(might take a minute to start... restart if longer)</span>)}<br/><br/></div>} {cliService.getCliMessage() && <Alert variant='info'>{cliService.getCliMessage()}</Alert>} <button type='button' className='btn btn-primary' onClick={this.reconnect}><FontAwesomeIcon icon={Icons.faSync} /> Retry to connect</button> {cliUrlError && <div> <br/> <Alert variant='danger'>Connection failed: {cliUrlError}</Alert> <br/><br/><br/><br/> <p>You may want to reset GUI settings.</p> <div className='text-center'> <button type='button' className='btn btn-danger btn-sm' onClick={this.onResetConfig}><FontAwesomeIcon icon={Icons.faExclamationTriangle} /> Reset {cliService.getResetLabel()}</button> </div> </div>} </form> ); } // connection failed onResetConfig() { if (confirm('This will reset '+cliService.getResetLabel()+'. Are you sure?')) { cliService.resetConfig() } } renderCliUrlError() { return ( <form className="form-signin text-center" onSubmit={(e) => {this.onSubmit();e.preventDefault()}}> <h1 className="h3 mb-3 font-weight-normal">Connecting...</h1> <div><FontAwesomeIcon icon={Icons.faWifi} size='3x' color='#343a40'/></div> <p>Connecting to whirlpool-cli...<br/> <strong>{cliService.getCliUrl()}</strong><br/> {cliService.isCliLocal() && <div>{cliLocalService.getStatusIcon((icon,text)=><span>{icon} {text}<br/>(might take a minute to start... restart if longer)</span>)}</div>} </p> </form> ); } } function mapStateToProps(state) { return { }; } function mapDispatchToProps (dispatch) { return { dispatch } } export default connect( mapStateToProps, mapDispatchToProps )(ConnectingPage);
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
// @flow import React, { Component } from 'react'; import { Provider } from 'react-redux'; import { ConnectedRouter } from 'connected-react-router'; import App from './App'; type Props = {}; export default class Root extends Component<Props> { render() { const { store, history } = this.props; return ( <Provider store={store}> <ConnectedRouter history={history}> <App /> </ConnectedRouter> </Provider> ); } }
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
// @flow import React, { Component } from 'react'; import { Alert, Card } from 'react-bootstrap'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import * as Icons from '@fortawesome/free-solid-svg-icons'; import { WHIRLPOOL_SERVER } from '../const'; import { logger } from '../utils/logger'; import { CliConfigService } from '../services/cliConfigService'; import cliService from '../services/cliService'; type Props = {}; const SERVER_MAIN = 'MAINNET' export default class ConfigPage extends Component<Props> { constructor(props) { super(props) this.state = { info: undefined, error: undefined, cliConfig: undefined, showDevelopersConfig: false } this.cliConfigService = new CliConfigService(cliConfig => this.setState({ cliConfig: cliConfig })) this.onResetConfig = this.onResetConfig.bind(this) this.onChangeCliConfig = this.onChangeCliConfig.bind(this) this.onSubmit = this.onSubmit.bind(this) this.toogleDevelopersConfig = this.toogleDevelopersConfig.bind(this) } onResetConfig() { if (confirm('This will reset '+cliService.getResetLabel()+'. Are you sure?')) { cliService.resetConfig() } } onChangeCliConfig(set) { const cliConfig = this.state.cliConfig set(this.state.cliConfig) this.setState({ cliConfig: cliConfig }) } onSubmit(e) { this.cliConfigService.save(this.state.cliConfig).then(() => { logger.info('Configuration updated') this.setState({ info: 'Configuration saved', error: undefined }) }).catch(e => { logger.error('', e) this.setState({ info: undefined, error: e.message }) }) } toogleDevelopersConfig() { this.setState({ showDevelopersConfig: !this.state.showDevelopersConfig }) } render() { if (!this.state.cliConfig) { return <small>Fetching CLI configuration...</small> } const cliConfig = this.state.cliConfig if (!cliConfig.mix) { cliConfig.mix = {} } const myThis = this const checked = e => { return e.target.checked } const clientsPerPoolEditable = cliConfig.server !== SERVER_MAIN return ( <div> <h1>Configuration</h1> <form onSubmit={(e) => {this.onSubmit(e);e.preventDefault()}}> <div className="form-group row"> <div className="col-sm-12"> {this.state.error && <Alert variant='danger'>{this.state.error}</Alert>} {this.state.info && <Alert variant='success'>{this.state.info}</Alert>} </div> </div> <Card> <Card.Header>CLI General configuration</Card.Header> <Card.Body> <div className="form-group row"> <label htmlFor="mixsTarget" className="col-sm-2 col-form-label">Mixs target min</label> <input type="number" className='form-control col-sm-3' onChange={e => { const myValue = parseInt(e.target.value) myThis.onChangeCliConfig(cliConfig => cliConfig.mix.mixsTarget = myValue) }} defaultValue={cliConfig.mix.mixsTarget} id="mixsTarget"/> <label className='col-form-label col-sm-5 text-muted'>Minimum number of mixs to achieve per UTXO</label> </div> <div className="form-group row"> <label htmlFor="autoMix" className="col-sm-2 col-form-label">Auto-MIX</label> <div className="col-sm-10 custom-control custom-switch"> <input type="checkbox" className="custom-control-input" onChange={e => myThis.onChangeCliConfig(cliConfig => cliConfig.mix.autoMix = checked(e))} defaultChecked={cliConfig.mix.autoMix} id="autoMix"/> <label className="custom-control-label" htmlFor="autoMix">Automatically mix premix & postmix</label> </div> </div> {cliService.isDojoPossible() && <div className="form-group row"> <label htmlFor="dojo" className="col-sm-2 col-form-label">DOJO</label> <div className="col-sm-10 custom-control custom-switch"> <input type="checkbox" className="custom-control-input" onChange={e => myThis.onChangeCliConfig(cliConfig => { cliConfig.dojo = checked(e) if (cliConfig.dojo) { cliConfig.tor = true } })} defaultChecked={cliConfig.dojo} id="dojo"/> <label className="custom-control-label" htmlFor="dojo">Enable DOJO <small>- {cliService.getDojoUrl()}</small></label> </div> </div>} <div className="form-group row"> <label htmlFor="tor" className="col-sm-2 col-form-label">Tor</label> {!cliConfig.dojo && <div className="col-sm-10 custom-control custom-switch"> <input type="checkbox" className="custom-control-input" onChange={e => myThis.onChangeCliConfig(cliConfig => cliConfig.tor = checked(e))} defaultChecked={cliConfig.tor} id="tor"/> <label className="custom-control-label" htmlFor="tor">Enable Tor</label> </div>} {cliConfig.dojo && <div className="col-sm-10"> DOJO+Tor enabled <FontAwesomeIcon icon={Icons.faCheck} color='green' /> </div>} </div> <div className="form-group row"> <label htmlFor="scode" className="col-sm-2 col-form-label">SCODE</label> <input type="text" className='form-control col-sm-3' onChange={e => { const myValue = e.target.value myThis.onChangeCliConfig(cliConfig => cliConfig.scode = myValue) }} defaultValue={cliConfig.scode} id="scode"/> <label className='col-form-label col-sm-5 text-muted'>A Samourai Discount Code for reduced-cost mixing.</label> </div> </Card.Body> </Card> <small><a onClick={this.toogleDevelopersConfig} style={{cursor:'pointer'}}>Toggle developers settings</a></small><br/> <br/> {this.state.showDevelopersConfig && <Card> <Card.Header>CLI Developers settings</Card.Header> <Card.Body> <div className="form-group row"> <label htmlFor="clientDelay" className="col-sm-2 col-form-label">Client delay</label> <input type="number" className='form-control col-sm-3' onChange={e => { const myValue = parseInt(e.target.value) myThis.onChangeCliConfig(cliConfig => cliConfig.mix.clientDelay = myValue) }} defaultValue={cliConfig.mix.clientDelay} id="clientDelay"/> <label className='col-form-label col-sm-5 text-muted'>Delay (in seconds) between each client connection</label> </div> <div className="form-group row"> <label htmlFor="tx0MaxOutputs" className="col-sm-2 col-form-label">TX0 max outputs</label> <input type="number" className='form-control col-sm-3' onChange={e => { const myValue = parseInt(e.target.value) myThis.onChangeCliConfig(cliConfig => cliConfig.mix.tx0MaxOutputs = myValue) }} defaultValue={cliConfig.mix.tx0MaxOutputs} id="tx0MaxOutputs"/> <label className='col-form-label col-sm-5 text-muted'>Max premixes per TX0 (0 = no limit)</label> </div> {clientsPerPoolEditable && <div className="form-group row"> <label htmlFor="clientsPerPool" className="col-sm-2 col-form-label">Max clients per pool</label> <input type="number" className='form-control col-sm-3' onChange={e => { const myValue = parseInt(e.target.value) myThis.onChangeCliConfig(cliConfig => cliConfig.mix.clientsPerPool = myValue) }} defaultValue={cliConfig.mix.clientsPerPool} id="clientsPerPool"/> <label className='col-form-label col-sm-5 text-muted'>Max simultaneous mixing clients per pool</label> </div>} <div className="form-group row"> <label htmlFor="proxy" className="col-sm-2 col-form-label">CLI proxy</label> <input type="text" className='form-control col-sm-3' onChange={e => { const myValue = e.target.value myThis.onChangeCliConfig(cliConfig => cliConfig.proxy = myValue) }} defaultValue={cliConfig.proxy} id="proxy"/> <label className='col-form-label col-sm-7 text-muted'> Set it only when blocked by a firewall (this is not <i>GUI Tor proxy</i>).<br/> <code>socks://host:port</code> or <code>http://host:port</code> </label> </div> <div className="form-group row"> <label htmlFor="server" className="col-sm-2 col-form-label">Server</label> <select className="col-sm-3 form-control" id="server" onChange={e => { const myValue = e.target.value myThis.onChangeCliConfig(cliConfig => cliConfig.server = myValue) }} defaultValue={cliConfig.server}> {Object.keys(WHIRLPOOL_SERVER).map((value) => <option value={value} key={value}>{WHIRLPOOL_SERVER[value]}</option>)} </select> </div> </Card.Body> </Card>} <br/> <div className="form-group row"> <div className="col-sm-5"> <button type='button' className='btn btn-danger' onClick={this.onResetConfig}><FontAwesomeIcon icon={Icons.faExclamationTriangle} /> Reset {cliService.getResetLabel()}</button> </div> <div className="col-sm-5"> <button type="submit" className="btn btn-primary">Save</button> </div> </div> </form> <br/><br/><br/><br/><br/> </div> ); } }
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
// @flow declare export default { [key: string]: string }
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
// @flow declare export default string
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
// @flow import chalk from 'chalk'; export default function CheckNodeEnv(expectedEnv: string) { if (!expectedEnv) { throw new Error('"expectedEnv" not set'); } if (process.env.NODE_ENV !== expectedEnv) { console.log( chalk.whiteBright.bgRed.bold( `"process.env.NODE_ENV" must be "${expectedEnv}" to use this webpack config` ) ); process.exit(2); } }
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
// @flow import chalk from 'chalk'; import detectPort from 'detect-port'; (function CheckPortInUse() { const port: string = process.env.PORT || '1212'; detectPort(port, (err: ?Error, availablePort: number) => { if (port !== String(availablePort)) { throw new Error( chalk.whiteBright.bgRed.bold( `Port "${port}" on "localhost" is already in use. Please use another port. ex: PORT=4343 yarn dev` ) ); } else { process.exit(0); } }); })();
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
// @flow // Check if the renderer and main bundles are built import path from 'path'; import chalk from 'chalk'; import fs from 'fs'; function CheckBuildsExist() { const mainPath = path.join(__dirname, '..', '..', 'app', 'main.prod.js'); const rendererPath = path.join( __dirname, '..', '..', 'app', 'dist', 'renderer.prod.js' ); if (!fs.existsSync(mainPath)) { throw new Error( chalk.whiteBright.bgRed.bold( 'The main process is not built yet. Build it by running "yarn build-main"' ) ); } if (!fs.existsSync(rendererPath)) { throw new Error( chalk.whiteBright.bgRed.bold( 'The renderer process is not built yet. Build it by running "yarn build-renderer"' ) ); } } CheckBuildsExist();
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
// @flow if (!/yarn\.js$/.test(process.env.npm_execpath || '')) { console.warn( "\u001b[33mYou don't seem to be using yarn. This could produce unexpected results.\u001b[39m" ); }
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
// @flow import fs from 'fs'; import chalk from 'chalk'; import { execSync } from 'child_process'; import { dependencies } from '../../package'; (() => { if (!dependencies) return; const dependenciesKeys = Object.keys(dependencies); const nativeDeps = fs .readdirSync('node_modules') .filter(folder => fs.existsSync(`node_modules/${folder}/binding.gyp`)); try { // Find the reason for why the dependency is installed. If it is installed // because of a devDependency then that is okay. Warn when it is installed // because of a dependency const { dependencies: dependenciesObject } = JSON.parse( execSync(`npm ls ${nativeDeps.join(' ')} --json`).toString() ); const rootDependencies = Object.keys(dependenciesObject); const filteredRootDependencies = rootDependencies.filter(rootDependency => dependenciesKeys.includes(rootDependency) ); if (filteredRootDependencies.length > 0) { const plural = filteredRootDependencies.length > 1; console.log(` ${chalk.whiteBright.bgYellow.bold( 'Webpack does not work with native dependencies.' )} ${chalk.bold(filteredRootDependencies.join(', '))} ${ plural ? 'are native dependencies' : 'is a native dependency' } and should be installed inside of the "./app" folder. First uninstall the packages from "./package.json": ${chalk.whiteBright.bgGreen.bold('yarn remove your-package')} ${chalk.bold( 'Then, instead of installing the package to the root "./package.json":' )} ${chalk.whiteBright.bgRed.bold('yarn add your-package')} ${chalk.bold('Install the package to "./app/package.json"')} ${chalk.whiteBright.bgGreen.bold('cd ./app && yarn add your-package')} Read more about native dependencies at: ${chalk.bold( 'https://github.com/electron-react-boilerplate/electron-react-boilerplate/wiki/Module-Structure----Two-package.json-Structure' )} `); process.exit(1); } } catch (e) { console.log('Native dependencies could not be checked'); } })();
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
const path = require('path'); require('@babel/register')({ cwd: path.join(__dirname, '..', '..') });
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
export default 'test-file-stub';
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
/** * Webpack config for production electron main process */ import path from 'path'; import webpack from 'webpack'; import merge from 'webpack-merge'; import TerserPlugin from 'terser-webpack-plugin'; import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer'; import baseConfig from './webpack.config.base'; import CheckNodeEnv from '../internals/scripts/CheckNodeEnv'; CheckNodeEnv('production'); export default merge.smart(baseConfig, { devtool: 'source-map', mode: 'production', target: 'electron-main', entry: './app/main.dev', output: { path: path.join(__dirname, '..'), filename: './app/main.prod.js' }, optimization: { minimizer: process.env.E2E_BUILD ? [] : [ new TerserPlugin({ parallel: true, sourceMap: true, cache: true }) ] }, plugins: [ new BundleAnalyzerPlugin({ analyzerMode: process.env.OPEN_ANALYZER === 'true' ? 'server' : 'disabled', openAnalyzer: process.env.OPEN_ANALYZER === 'true' }), /** * Create global constants which can be configured at compile time. * * Useful for allowing different behaviour between development builds and * release builds * * NODE_ENV should be production so that modules do not perform certain * development checks */ new webpack.EnvironmentPlugin({ NODE_ENV: 'production', DEBUG_PROD: false, START_MINIMIZED: false }) ], /** * Disables webpack processing of __dirname and __filename. * If you run the bundle in node.js it falls back to these values of node.js. * https://github.com/webpack/webpack/issues/2010 */ node: { __dirname: false, __filename: false } });
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
/** * Build config for electron renderer process */ import path from 'path'; import webpack from 'webpack'; import MiniCssExtractPlugin from 'mini-css-extract-plugin'; import OptimizeCSSAssetsPlugin from 'optimize-css-assets-webpack-plugin'; import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer'; import merge from 'webpack-merge'; import TerserPlugin from 'terser-webpack-plugin'; import baseConfig from './webpack.config.base'; import CheckNodeEnv from '../internals/scripts/CheckNodeEnv'; CheckNodeEnv('production'); export default merge.smart(baseConfig, { devtool: 'source-map', mode: 'production', target: 'electron-renderer', entry: path.join(__dirname, '..', 'app/index'), output: { path: path.join(__dirname, '..', 'app/dist'), publicPath: './dist/', filename: 'renderer.prod.js' }, module: { rules: [ // Extract all .global.css to style.css as is { test: /\.global\.css$/, use: [ { loader: MiniCssExtractPlugin.loader, options: { publicPath: './' } }, { loader: 'css-loader', options: { sourceMap: true } } ] }, // Pipe other styles through css modules and append to style.css { test: /^((?!\.global).)*\.css$/, use: [ { loader: MiniCssExtractPlugin.loader }, { loader: 'css-loader', options: { modules: { localIdentName: '[name]__[local]__[hash:base64:5]' }, sourceMap: true } } ] }, // Add SASS support - compile all .global.scss files and pipe it to style.css { test: /\.global\.(scss|sass)$/, use: [ { loader: MiniCssExtractPlugin.loader }, { loader: 'css-loader', options: { sourceMap: true, importLoaders: 1 } }, { loader: 'sass-loader', options: { sourceMap: true } } ] }, // Add SASS support - compile all other .scss files and pipe it to style.css { test: /^((?!\.global).)*\.(scss|sass)$/, use: [ { loader: MiniCssExtractPlugin.loader }, { loader: 'css-loader', options: { modules: { localIdentName: '[name]__[local]__[hash:base64:5]' }, importLoaders: 1, sourceMap: true } }, { loader: 'sass-loader', options: { sourceMap: true } } ] }, // WOFF Font { test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, use: { loader: 'url-loader', options: { limit: 10000, mimetype: 'application/font-woff' } } }, // WOFF2 Font { test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, use: { loader: 'url-loader', options: { limit: 10000, mimetype: 'application/font-woff' } } }, // TTF Font { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, use: { loader: 'url-loader', options: { limit: 10000, mimetype: 'application/octet-stream' } } }, // EOT Font { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, use: 'file-loader' }, // SVG Font { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, use: { loader: 'url-loader', options: { limit: 10000, mimetype: 'image/svg+xml' } } }, // Common Image Formats { test: /\.(?:ico|gif|png|jpg|jpeg|webp)$/, use: 'url-loader' } ] }, optimization: { minimizer: process.env.E2E_BUILD ? [] : [ new TerserPlugin({ parallel: true, sourceMap: true, cache: true }), new OptimizeCSSAssetsPlugin({ cssProcessorOptions: { map: { inline: false, annotation: true } } }) ] }, plugins: [ /** * Create global constants which can be configured at compile time. * * Useful for allowing different behaviour between development builds and * release builds * * NODE_ENV should be production so that modules do not perform certain * development checks */ new webpack.EnvironmentPlugin({ NODE_ENV: 'production' }), new MiniCssExtractPlugin({ filename: 'style.css' }), new BundleAnalyzerPlugin({ analyzerMode: process.env.OPEN_ANALYZER === 'true' ? 'server' : 'disabled', openAnalyzer: process.env.OPEN_ANALYZER === 'true' }) ] });
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
/* eslint global-require: off, import/no-dynamic-require: off */ /** * Build config for development electron renderer process that uses * Hot-Module-Replacement * * https://webpack.js.org/concepts/hot-module-replacement/ */ import path from 'path'; import fs from 'fs'; import webpack from 'webpack'; import chalk from 'chalk'; import merge from 'webpack-merge'; import { spawn, execSync } from 'child_process'; import baseConfig from './webpack.config.base'; import CheckNodeEnv from '../internals/scripts/CheckNodeEnv'; CheckNodeEnv('development'); const port = process.env.PORT || 1212; const publicPath = `http://localhost:${port}/dist`; const dll = path.join(__dirname, '..', 'dll'); const manifest = path.resolve(dll, 'renderer.json'); const requiredByDLLConfig = module.parent.filename.includes( 'webpack.config.renderer.dev.dll' ); /** * Warn if the DLL is not built */ if (!requiredByDLLConfig && !(fs.existsSync(dll) && fs.existsSync(manifest))) { console.log( chalk.black.bgYellow.bold( 'The DLL files are missing. Sit back while we build them for you with "yarn build-dll"' ) ); execSync('yarn build-dll'); } export default merge.smart(baseConfig, { devtool: 'inline-source-map', mode: 'development', target: 'electron-renderer', entry: [ 'react-hot-loader/patch', `webpack-dev-server/client?http://localhost:${port}/`, 'webpack/hot/only-dev-server', require.resolve('../app/index') ], output: { publicPath: `http://localhost:${port}/dist/`, filename: 'renderer.dev.js' }, module: { rules: [ { test: /\.jsx?$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { cacheDirectory: true } } }, { test: /\.global\.css$/, use: [ { loader: 'style-loader' }, { loader: 'css-loader', options: { sourceMap: true } } ] }, { test: /^((?!\.global).)*\.css$/, use: [ { loader: 'style-loader' }, { loader: 'css-loader', options: { modules: { localIdentName: '[name]__[local]__[hash:base64:5]' }, sourceMap: true, importLoaders: 1 } } ] }, // SASS support - compile all .global.scss files and pipe it to style.css { test: /\.global\.(scss|sass)$/, use: [ { loader: 'style-loader' }, { loader: 'css-loader', options: { sourceMap: true } }, { loader: 'sass-loader' } ] }, // SASS support - compile all other .scss files and pipe it to style.css { test: /^((?!\.global).)*\.(scss|sass)$/, use: [ { loader: 'style-loader' }, { loader: 'css-loader', options: { modules: { localIdentName: '[name]__[local]__[hash:base64:5]' }, sourceMap: true, importLoaders: 1, } }, { loader: 'sass-loader' } ] }, // WOFF Font { test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, use: { loader: 'url-loader', options: { limit: 10000, mimetype: 'application/font-woff' } } }, // WOFF2 Font { test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, use: { loader: 'url-loader', options: { limit: 10000, mimetype: 'application/font-woff' } } }, // TTF Font { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, use: { loader: 'url-loader', options: { limit: 10000, mimetype: 'application/octet-stream' } } }, // EOT Font { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, use: 'file-loader' }, // SVG Font { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, use: { loader: 'url-loader', options: { limit: 10000, mimetype: 'image/svg+xml' } } }, // Common Image Formats { test: /\.(?:ico|gif|png|jpg|jpeg|webp)$/, use: 'url-loader' } ] }, plugins: [ requiredByDLLConfig ? null : new webpack.DllReferencePlugin({ context: path.join(__dirname, '..', 'dll'), manifest: require(manifest), sourceType: 'var' }), new webpack.HotModuleReplacementPlugin({ multiStep: true }), new webpack.NoEmitOnErrorsPlugin(), /** * Create global constants which can be configured at compile time. * * Useful for allowing different behaviour between development builds and * release builds * * NODE_ENV should be production so that modules do not perform certain * development checks * * By default, use 'development' as NODE_ENV. This can be overriden with * 'staging', for example, by changing the ENV variables in the npm scripts */ new webpack.EnvironmentPlugin({ NODE_ENV: 'development' }), new webpack.LoaderOptionsPlugin({ debug: true }) ], node: { __dirname: false, __filename: false }, devServer: { port, publicPath, compress: true, noInfo: true, stats: 'errors-only', inline: true, lazy: false, hot: true, headers: { 'Access-Control-Allow-Origin': '*' }, contentBase: path.join(__dirname, 'dist'), watchOptions: { aggregateTimeout: 300, ignored: /node_modules/, poll: 100 }, historyApiFallback: { verbose: true, disableDotRule: false }, before() { if (process.env.START_HOT) { console.log('Starting Main Process...'); spawn('npm', ['run', 'start-main-dev'], { shell: true, env: process.env, stdio: 'inherit' }) .on('close', code => process.exit(code)) .on('error', spawnError => console.error(spawnError)); } } } });
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
/* eslint import/no-unresolved: off, import/no-self-import: off */ require('@babel/register'); module.exports = require('./webpack.config.renderer.dev.babel').default;
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
/* eslint global-require: off, import/no-dynamic-require: off */ /** * Builds the DLL for development electron renderer process */ import webpack from 'webpack'; import path from 'path'; import merge from 'webpack-merge'; import baseConfig from './webpack.config.base'; import { dependencies } from '../package.json'; import CheckNodeEnv from '../internals/scripts/CheckNodeEnv'; CheckNodeEnv('development'); const dist = path.join(__dirname, '..', 'dll'); export default merge.smart(baseConfig, { context: path.join(__dirname, '..'), devtool: 'eval', mode: 'development', target: 'electron-renderer', externals: ['fsevents', 'crypto-browserify'], /** * Use `module` from `webpack.config.renderer.dev.js` */ module: require('./webpack.config.renderer.dev.babel').default.module, entry: { renderer: Object.keys(dependencies || {}) }, output: { library: 'renderer', path: dist, filename: '[name].dev.dll.js', libraryTarget: 'var' }, plugins: [ new webpack.DllPlugin({ path: path.join(dist, '[name].json'), name: '[name]' }), /** * Create global constants which can be configured at compile time. * * Useful for allowing different behaviour between development builds and * release builds * * NODE_ENV should be production so that modules do not perform certain * development checks */ new webpack.EnvironmentPlugin({ NODE_ENV: 'development' }), new webpack.LoaderOptionsPlugin({ debug: true, options: { context: path.join(__dirname, '..', 'app'), output: { path: path.join(__dirname, '..', 'dll') } } }) ] });
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
/** * Base webpack config used across other specific configs */ import path from 'path'; import webpack from 'webpack'; import { dependencies } from '../package.json'; export default { externals: [...Object.keys(dependencies || {})], module: { rules: [ { test: /\.jsx?$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { cacheDirectory: true } } } ] }, output: { path: path.join(__dirname, '..', 'app'), // https://github.com/webpack/webpack/issues/1114 libraryTarget: 'commonjs2' }, /** * Determine the array of extensions that should be used to resolve modules. */ resolve: { extensions: ['.js', '.jsx', '.json'], modules: [path.join(__dirname, '..', 'app'), 'node_modules'] }, plugins: [ new webpack.EnvironmentPlugin({ NODE_ENV: 'production' }), new webpack.NamedModulesPlugin() ] };
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
declare module 'module' { declare module.exports: any; }
{ "repo_name": "Samourai-Wallet/whirlpool-gui", "stars": "56", "repo_language": "JavaScript", "file_name": "module_vx.x.x.js", "mime_type": "text/plain" }
# PonchoOS Git repo of the Operating System tutorial series by Poncho
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
The files in the "lib" and "inc" subdirectories are using the EFI Application Toolkit distributed by Intel at http://developer.intel.com/technology/efi This code is covered by the following agreement: Copyright (c) 1998-2000 Intel Corporation Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL INTEL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE EFI SPECIFICATION AND ALL OTHER INFORMATION ON THIS WEB SITE ARE PROVIDED "AS IS" WITH NO WARRANTIES, AND ARE SUBJECT TO CHANGE WITHOUT NOTICE.
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
# # Copyright (C) 1999-2007 Hewlett-Packard Co. # Contributed by David Mosberger <[email protected]> # Contributed by Stephane Eranian <[email protected]> # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials # provided with the distribution. # * Neither the name of Hewlett-Packard Co. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND # CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, # INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS # BE LIABLE FOR ANYDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, # OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF # THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # %.efi: %.so $(OBJCOPY) -j .text -j .sdata -j .data -j .dynamic -j .dynsym -j .rel \ -j .rela -j .rel.* -j .rela.* -j .rel* -j .rela* \ -j .reloc $(FORMAT) $*.so $@ %.efi.debug: %.so $(OBJCOPY) -j .debug_info -j .debug_abbrev -j .debug_aranges \ -j .debug_line -j .debug_str -j .debug_ranges \ -j .note.gnu.build-id \ $(FORMAT) $*.so $@ %.so: %.o $(LD) $(LDFLAGS) $^ -o $@ $(LOADLIBES) %.o: %.c $(CC) $(INCDIR) $(CFLAGS) $(CPPFLAGS) -c $< -o $@ %.s: %.c $(CC) $(INCDIR) $(CFLAGS) $(CPPFLAGS) -S $< -o $@ %.i: %.c $(CC) $(INCDIR) $(CFLAGS) $(CPPFLAGS) -E $< -o $@ %.o: %.S $(CC) $(INCDIR) $(CFLAGS) $(CPPFLAGS) -c $< -o $@ %.s: %.S $(CC) $(INCDIR) $(CFLAGS) $(CPPFLAGS) -E $< -o $@
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
# # Copyright (C) 1999-2007 Hewlett-Packard Co. # Contributed by David Mosberger <[email protected]> # Contributed by Stephane Eranian <[email protected]> # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials # provided with the distribution. # * Neither the name of Hewlett-Packard Co. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND # CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, # INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS # BE LIABLE FOR ANYDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, # OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF # THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # VERSION = 3.0.12 MKFILE_PATH := $(abspath $(lastword $(MAKEFILE_LIST))) SRCDIR = $(dir $(MKFILE_PATH)) VPATH = $(SRCDIR) include $(SRCDIR)/Make.defaults SUBDIRS = lib gnuefi inc apps bootloader gnuefi: lib all: check_gcc $(SUBDIRS) mkvars: @echo AR=$(AR) @echo ARCH=$(ARCH) @echo ARCH3264=$(ARCH3264) @echo AS=$(AS) @echo ASFLAGS=$(ASFLAGS) @echo CC=$(CC) @echo CFLAGS=$(CFLAGS) @echo CPPFLAGS=$(CPPFLAGS) @echo GCCMINOR=$(GCCMINOR) @echo GCCNEWENOUGH=$(GCCNEWENOUGH) @echo GCCVERSION=$(GCCVERSION) @echo HOSTARCH=$(HOSTARCH) @echo INCDIR=$(INCDIR) @echo INSTALL=$(INSTALL) @echo INSTALLROOT=$(INSTALLROOT) @echo LD=$(LD) @echo LDFLAGS=$(LDFLAGS) @echo LIBDIR=$(LIBDIR) @echo OBJCOPY=$(OBJCOPY) @echo OS=$(OS) @echo prefix=$(prefix) @echo PREFIX=$(PREFIX) @echo RANLIB=$(RANLIB) @echo SRCDIR=$(SRCDIR) @echo TOPDIR=$(TOPDIR) $(SUBDIRS): mkdir -p $(OBJDIR)/$@ $(MAKE) -C $(OBJDIR)/$@ -f $(SRCDIR)/$@/Makefile SRCDIR=$(SRCDIR)/$@ ARCH=$(ARCH) clean: rm -f *~ @for d in $(SUBDIRS); do \ if [ -d $(OBJDIR)/$$d ]; then \ $(MAKE) -C $(OBJDIR)/$$d -f $(SRCDIR)/$$d/Makefile SRCDIR=$(SRCDIR)/$$d clean; \ fi; \ done install: @for d in $(SUBDIRS); do \ mkdir -p $(OBJDIR)/$$d; \ $(MAKE) -C $(OBJDIR)/$$d -f $(SRCDIR)/$$d/Makefile SRCDIR=$(SRCDIR)/$$d install; done .PHONY: $(SUBDIRS) clean depend # # on both platforms you must use gcc 3.0 or higher # check_gcc: ifeq ($(GCC_VERSION),2) @echo "you need to use a version of gcc >= 3.0, you are using `$(CC) --version`" @exit 1 endif include $(SRCDIR)/Make.rules test-archive: @rm -rf /tmp/gnu-efi-$(VERSION) /tmp/gnu-efi-$(VERSION)-tmp @mkdir -p /tmp/gnu-efi-$(VERSION)-tmp @git archive --format=tar $(shell git branch | awk '/^*/ { print $$2 }') | ( cd /tmp/gnu-efi-$(VERSION)-tmp/ ; tar x ) @git diff | ( cd /tmp/gnu-efi-$(VERSION)-tmp/ ; patch -s -p1 -b -z .gitdiff ) @mv /tmp/gnu-efi-$(VERSION)-tmp/ /tmp/gnu-efi-$(VERSION)/ @dir=$$PWD; cd /tmp; tar -c --bzip2 -f $$dir/gnu-efi-$(VERSION).tar.bz2 gnu-efi-$(VERSION) @rm -rf /tmp/gnu-efi-$(VERSION) @echo "The archive is in gnu-efi-$(VERSION).tar.bz2" tag: git tag $(VERSION) refs/heads/master archive: tag @rm -rf /tmp/gnu-efi-$(VERSION) /tmp/gnu-efi-$(VERSION)-tmp @mkdir -p /tmp/gnu-efi-$(VERSION)-tmp @git archive --format=tar $(VERSION) | ( cd /tmp/gnu-efi-$(VERSION)-tmp/ ; tar x ) @mv /tmp/gnu-efi-$(VERSION)-tmp/ /tmp/gnu-efi-$(VERSION)/ @dir=$$PWD; cd /tmp; tar -c --bzip2 -f $$dir/gnu-efi-$(VERSION).tar.bz2 gnu-efi-$(VERSION) @rm -rf /tmp/gnu-efi-$(VERSION) @echo "The archive is in gnu-efi-$(VERSION).tar.bz2"
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
IMPORTANT information related to the gnu-efi package ---------------------------------------------------- June 2001 As of version 3.0, the gnu-efi package is now split in two different packages: -> gnu-efi-X.y: contains the EFI library, include files and crt0. -> elilo-X.y : contains the ELILO bootloader. Note that X.y don't need to match for both packages. However elilo-3.x requires at least gnu-efi-3.0. EFI support for x86_64 is provided in gnu-efi-3.0d. Both packages can be downloaded from: http://www.sf.net/projects/gnu-efi http://www.sf.net/projects/elilo
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
Updated Changelog Signed-off-by: Nigel Croxon <[email protected]> commit 37d7bee82a627999563069b090866076e055a871 Author: Nigel Croxon <[email protected]> Date: Thu May 14 12:38:39 2015 -0400 Added some missing error code descriptions Signed-off-by: Peter Jones <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> commit dae0b4b0b0d522caecf09123db2cf0250c37a169 Author: Nigel Croxon <[email protected]> Date: Thu May 14 12:20:51 2015 -0400 Turns out we actually need setjmp in one of gnu-efi's prominent users, and it seems to make more sense to put it here than in the application. All of these are derived from the Tiano code, but I re-wrote the x86_64 one because we use the ELF psABI calling conventions instead of the MS ABI calling conventions. Which is to say you probably shouldn't setjmp()/longjmp() between functions with EFIAPI (aka __attribute__((ms_abi))) and those without. Signed-off-by: Peter Jones <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> commit b5a8e93cec396381a6d2beee022abbf50100f2fd Author: Nigel Croxon <[email protected]> Date: Fri Apr 10 08:49:50 2015 -0400 Bump version to 3.0.2 Signed-off-by: Nigel Croxon <[email protected]> commit 01c9f11ed5ad55661e8fc8a3eee35c578564754b Author: Nigel Croxon <[email protected]> Date: Fri Apr 10 08:46:40 2015 -0400 Fix ARM32 and AARCH64 builds Without these added into SUBDIRS the initplat.c compilation will fail. Signed-off-by: Koen Kooi <[email protected]> Acked-by: Ard Biesheuvel <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> commit dada63fd3de148c6f8551d253355c113547cd5a0 Author: Nigel Croxon <[email protected]> Date: Mon Mar 23 10:41:43 2015 -0400 [PATCH] _SPrint: fix NULL termination maxlen is the maximum string length not the buffer size. Signed-off-by: Jeremy Compostella <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> commit ce7098fb52e5fd4d16038964d029eb759f28eaaf Author: Nigel Croxon <[email protected]> Date: Thu Feb 19 11:22:45 2015 -0500 Enable out-of-tree building This patch enables building gnu-efi outside of the source tree. That in turn enables building for multiple architectures in parallel. The build directory is controlled by the OBJDIR make variable. It defaults to the value of ARCH, and can be overridden from the command line. This patch also cleans up some doubled slashes between INSTALLROOT and PREFIX. Signed-off-by: Jonathan Boeing <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> commit f64cef26270bfbe04f038da33f95ae3f14c071bc Author: Nigel Croxon <[email protected]> Date: Tue Jan 6 15:49:50 2015 -0500 Since we're keeping this in git, it'd be nice not to see a bunch of make targets in 'status' Signed-off-by: Peter Jones <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> commit 322efb6b21ed0a5e42e8f124fd22bf0f8dbf01ae Author: Nigel Croxon <[email protected]> Date: Mon Jan 5 13:20:43 2015 -0500 version number changed from VERSION = 3.0u to VERSION = 3.0.1 Signed-off-by: Nigel Croxon <[email protected]> commit 09027207f7c18af6caa45a744fc15c90b2a829db Author: Nigel Croxon <[email protected]> Date: Mon Jan 5 13:13:22 2015 -0500 From: Pete Batard <[email protected]> Date: Wed, 10 Dec 2014 21:08:34 +0000 Subject: [PATCH] fixes for MSVC compilation These fixes are needed to address the following error and warnings when compiling the library part using Visual Studio 2013 Community Edition (as in https://github.com/pbatard/uefi-simple): * "lib\x86_64\math.c(49): error C4235: nonstandard extension used : '_asm' keyword not supported on this architecture" * "lib\print.c(98): error C2059: syntax error : '('" due to placement of EFIAPI macro * "lib\cmdline.c(94): warning C4090: 'function' : different 'const' qualifiers" * "lib\smbios.c(25): warning C4068: unknown pragma" * Also update macro definitions in "inc\<arch>\efibind.h" for MSVC Signed-off-by: Pete Batard <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> commit 15805ff38b83a72c2c7c96a24bd642ee1176d819 Author: Nigel Croxon <[email protected]> Date: Tue Nov 25 14:23:21 2014 -0500 Add README.git file. Instructions on how to archive. Signed-off-by: Nigel Croxon <[email protected]> commit b868aa75669723b7e32f46524822e17e388fe2ba Author: Nigel Croxon <[email protected]> Date: Tue Nov 25 13:26:45 2014 -0500 This patch makes generating releases from git a very simple process; you simply edit the makefile's "VERSION" line to the new version, commit that as its own commit, and do: "make test-archive". That'll make a file in the current directory gnu-efi-$VERSION.tar.bz2 , with its top level directory gnu-efi-$VERSION/ and the source tree under that. Once you've tested that and you're sure it's what you want to release, you do "make archive", which will tag a release in git and generate a final tarball from it. You then push to the archive, being sure to include the tag: git push origin master:master --tags And upload the archive wherever it's supposed to go. Signed-off-by: Peter Jones <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> commit 530d68ba191850edafc6da22cb2df55bec0c5fa5 Author: Nigel Croxon <[email protected]> Date: Tue Nov 25 10:09:50 2014 -0500 The gnu-efi-3.0 toplevel subdirectory is really annoying. Kill it. Signed-off-by: Peter Jones <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> commit 00bd66ef46b59a1623a293491a8b2c65a6d61975 Author: Nigel Croxon <[email protected]> Date: Mon Nov 24 14:33:09 2014 -0500 FreeBSD's binutils doesn't have "-j <glob>" support, so we need to include non-globbed versions of .rel/.rela individually. Signed-off-by: Peter Jones <[email protected]> Signed-off-by: Bill Paul <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> commit 56eb64d3c06854b9b68d61e3c2d3bdf6ff2a9853 Author: Nigel Croxon <[email protected]> Date: Mon Nov 24 14:27:14 2014 -0500 Right now we wind up trying to build gnuefi/.o from a source file that's an empty string. This is caused by the macros trying to generate install rules, but there's no real reason to have all that anyway. So just have some static install rules that are simpler and don't generate stuff on the fly. Signed-off-by: Peter Jones <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> commit 65e28a90a7be9e990b360286cea31e63319217fb Author: Nigel Croxon <[email protected]> Date: Mon Nov 24 12:17:45 2014 -0500 Add current OsIndications values. Signed-off-by: Peter Jones <[email protected]> Signed-off-by: Nigel Croxon <[email protected] commit be231055ce14d17610f0d7b6133a87b99a22662b Author: Nigel Croxon <[email protected]> Date: Mon Nov 24 12:15:34 2014 -0500 Add the QueryVariableInfo() API. Signed-off-by: Peter Jones <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> commit 60efb7a2939b65a01e95aa8b535f1b756d984fba Author: Nigel Croxon <[email protected]> Date: Mon Nov 24 12:13:23 2014 -0500 Add the capsule API. Signed-off-by: Peter Jones <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> commit ef08b655d1f8dfbd9a0f3a86d5685b24695ef12f Author: Nigel Croxon <[email protected]> Date: Mon Nov 17 16:05:42 2014 -0500 Fix Table Header misspelling. Change from EFI_TABLE_HEARDER to EFI_TABLE_HEADER. Signed-Off-By: Nigel Croxon <[email protected]> commit 370cce41da3fff41ba38feb1262002aff2d85ffd Author: Nigel Croxon <[email protected]> Date: Thu Nov 6 14:41:40 2014 -0500 If CROSS_COMPILE is set, ignore the ARCH value supplied on the command line and use the target machine of the cross compiler. Signed-off-by: Ard Biesheuvel <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> commit d32fb845433ff6fb38e81ae0d9273454e7d18197 Author: Nigel Croxon <[email protected]> Date: Thu Nov 6 14:30:03 2014 -0500 Allow reuse of this file beyond GPL compatible software, update the license of crt0-efi-aarch64.S to dual 2-clause BSD/GPLv2+. Signed-off-by: Ard Biesheuvel <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> commit aa1df67f48f3c035fa8891e1bb311ec21500d6d9 Author: Nigel Croxon <[email protected]> Date: Tue Oct 21 11:08:47 2014 -0400 Add the missing Variable attributes From: Jeremy Compostella <[email protected]> Date: Mon, 13 Oct 2014 17:50:50 +0200 Subject: [PATCH] Add the missing Variable attributes Signed-off-by: Jeremy Compostella <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> commit 5706dff09364cbbec37f47e2fe1350747f631d74 Author: Nigel Croxon <[email protected]> Date: Tue Aug 26 10:54:22 2014 -0400 From: David Decotigny <[email protected]> Date: Mon, 25 Aug 2014 13:28:49 -0700 Subject: [PATCH] document that binutils >= 2.24 needed. commit ac983081 "Add support for non-PE/COFF capable objcopy" depends on objcopy accepting wildcards for the section names. This feature is available only with binutils >= 2.24 (binutils 2e62b7218 "PR binutils/15033"). Signed-off-by: David Decotigny <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> commit 6c10e225bc759d69af520a551b9d7b37f3ae0a82 Author: Nigel Croxon <[email protected]> Date: Mon Aug 25 08:51:23 2014 -0400 From: David Decotigny <[email protected]> Date: Thu, 31 Jul 2014 18:19:16 -0700 Subject: [PATCH 5/5] allow to use external stdarg.h in cases we use gnu-efi together with other libs that define stdarg.h, break the tie by telling gnu-efi to use that stdarg.h . Signed-off-by: David Decotigny <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> commit 16d65c0669258c8044e3549b2d9eb0cf0eb08f5a Author: Nigel Croxon <[email protected]> Date: Tue Aug 19 12:07:00 2014 -0400 From: Ard Biesheuvel <[email protected]> Date: Mon, 11 Aug 2014 15:39:16 +0200 Subject: [PATCH] Add support for 32-bit ARM This adds support for 32-bit ARM using an approach similar to the one used for 64-bit ARM (AArch64), i.e., it does not rely on an objcopy that is aware of EFI or PE/COFF, but lays out the entire PE/COFF header using the assembler. In the 32-bit ARM case (which does not have a division instruction), some code has been imported from the Linux kernel to perform the division operations in software. Signed-off-by: Ard Biesheuvel <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> commit b28143d4fb4f6969dc0c87c853d3527d889951d7 Author: Nigel Croxon <[email protected]> Date: Fri Aug 8 15:54:19 2014 -0400 Updated Changelog Signed-off-by: Nigel Croxon <[email protected]> commit 1525190354f5faac33015e17c9ba7ea2bb2be35b Author: Nigel Croxon <[email protected]> Date: Fri Aug 8 15:35:09 2014 -0400 From: Ard Biesheuvel <[email protected]> Date: Fri, 8 Aug 2014 18:16:59 +0200 Subject: [PATCH 4/4] Add support for 64-bit ARM (AArch64) This adds support for 64-bit ARM (AArch64) environments. Since there is no EFI-capable objcopy for this platform, this contains a manually laid out PE/COFF header using the assembler. In addition, it includes the relocation bits, some string functions that GCC assumes are available and other glue to hold it all together. This can be cross built using make CROSS_COMPILE=aarch64-linux-gnu- Signed-off-by: Ard Biesheuvel <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> commit ac983081525f9483941517dfb53cf8d0163d49c0 Author: Nigel Croxon <[email protected]> Date: Fri Aug 8 15:32:26 2014 -0400 From: Ard Biesheuvel <[email protected]> Date: Fri, 8 Aug 2014 17:53:42 +0200 Subject: [PATCH 3/4] Add support for non-PE/COFF capable objcopy Introduce HAVE_EFI_OBJCOPY and set it if objcopy for $ARCH support PE/COOF and EFI, i.e., it supports --target efi-[app|bsdrv|rtdrv] options. Use it to decide whether to invoke objcopy with those options or use the linker to populate the PE/COFF header. Signed-off-by: Ard Biesheuvel <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> commit fb063f0f65543b3e2bf55a39d5aa70b17a98c65e Author: Nigel Croxon <[email protected]> Date: Fri Aug 8 15:26:38 2014 -0400 From: Ard Biesheuvel <[email protected]> Date: Fri, 8 Aug 2014 17:37:36 +0200 Subject: [PATCH 2/4] Add support for cross compilation This changes the logic that defines ARCH (and HOSTARCH) to take CROSS_COMPILE into account. Also, $prefix is not assigned, so that the default will be what is on the path rather than hardcoded in /usr/bin. This results in the build doing the right thing if CROSS_COMPILE is set in the environment and no ARCH or prefix options are passed to make, aligning it with most other CROSS_COMPILE compatible projects. Signed-off-by: Ard Biesheuvel <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> commit 7a98d83fc32de6cf0b1ce5e12dfe80690f29fb3f Author: Nigel Croxon <[email protected]> Date: Fri Aug 8 15:25:03 2014 -0400 From: Ard Biesheuvel <[email protected]> Date: Fri, 8 Aug 2014 16:50:45 +0200 Subject: [PATCH 1/4] Restrict GNU_EFI_USE_MS_ABI GCC version test to x86_64 The version test only applies to x86_64 builds, so no need to do it for other archs. Signed-off-by: Ard Biesheuvel <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> commit f42974dd9a7d0ea690d293f88396abd289f0014c Author: Nigel Croxon <[email protected]> Date: Fri Aug 8 15:21:16 2014 -0400 From: David Decotigny <[email protected]> Date: Thu, 31 Jul 2014 13:42:23 -0700 Subject: [PATCH 4/4] Use Shell protocols to retrieve argc/argv, when available. New header files efishellintf.h efishellparm.h are coming from EDK II, initial location and license at top of files. Only modifications: - efishellintf.h: s/EFI_FILE_PROTOCOL/EFI_FILE/ + expand BITx macros (1<<x) - efishellparm.h: typedef VOID *SHELL_FILE_HANDLE to avoid including ShellBase.h - both: removed extern EFI_GUID variable decls This also adds apps/t8.c, a simple demo. Signed-off-by: David Decotigny <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> commit a61fa058e9a87f966de3342b8c95fdbdcb007827 Author: Nigel Croxon <[email protected]> Date: Fri Aug 8 15:17:32 2014 -0400 From: David Decotigny <[email protected]> Date: Thu, 31 Jul 2014 13:41:52 -0700 Subject: [PATCH 3/4] document format of LoadedImage::LoadOptions data Signed-off-by: David Decotigny <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> commit 2f440200c855154f929d28971b2fd702ea7a207a Author: Nigel Croxon <[email protected]> Date: Fri Aug 8 15:15:59 2014 -0400 From: David Decotigny <[email protected]> Date: Thu, 31 Jul 2014 13:39:37 -0700 Subject: [PATCH 2/4] Use OpenProtocol instead of HandleProtocol UEFI 2.x recommends OpenProtocol instead of HandleProtocol. Signed-off-by: David Decotigny <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> commit 7f173da1e54f8cfe4c7c7c091ab6585af07b25ce Author: Nigel Croxon <[email protected]> Date: Fri Aug 8 15:14:26 2014 -0400 From: David Decotigny <[email protected]> Date: Thu, 31 Jul 2014 13:30:07 -0700 Subject: [PATCH 1/4] move cmdline parser to its own file Signed-off-by: David Decotigny <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> commit 0ad8fb87cbc59f58675b18253ad802ba51f1d132 Author: Nigel Croxon <[email protected]> Date: Wed Jul 30 15:06:36 2014 -0400 From: David Decotigny <[email protected]> Date: Mon, 28 Jul 2014 21:28:50 -0700 Subject: [PATCH 3/3] make cmdline parsing a 1st class citizen Refactor ParseCmdline and apps/Alloc+FreePages to factorize boilerplate and move the new parser to the main API. Signed-off-by: David Decotigny <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> commit ff7ec964f2c0de0cfc4b52cfdd356003450f28bf Author: Nigel Croxon <[email protected]> Date: Wed Jul 30 15:05:28 2014 -0400 From: David Decotigny <[email protected]> Date: Mon, 28 Jul 2014 21:00:52 -0700 Subject: [PATCH 2/3] Avoid buffer overflow while parsing the cmdline args Signed-off-by: David Decotigny <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> commit 8d86ee202a9bb553375f56ae1d2944818112b68b Author: Nigel Croxon <[email protected]> Date: Wed Jul 30 15:04:44 2014 -0400 From: David Decotigny <[email protected]> Date: Mon, 28 Jul 2014 21:01:35 -0700 Subject: [PATCH 1/3] Fix cmdline parser The cmdline parser would not return the correct number of args, would allocate one too many. Also make it clear from the declaration that we expect a suitably lare argv. Signed-off-by: David Decotigny <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> commit 1ec094bfaf46a610a740dadc0150bf457dd72345 Author: Nigel Croxon <[email protected]> Date: Wed Jul 23 09:54:25 2014 -0400 From: Julian Klode <[email protected]> Date: Mon, 21 Jul 2014 14:26:23 -0400 Subject: [PATCH] inc/efistdarg.h: Use gcc builtins instead of stdarg.h or broken stubs We cannot use stdarg.h, as this breaks applications compiling with -nostdinc because those will not find the header. We also cannot use the stubs, as they just produce broken code, as seen in the gummiboot 45-1 Debian release. Signed-off-by: Julian Klode <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> commit 6caab22f23434f41f42cfe7591d9a7ae66de9f0a Author: Nigel Croxon <[email protected]> Date: Thu Jun 19 10:39:23 2014 -0400 From: Laszlo Ersek <[email protected]> Date: Mon, 2 Jun 2014 23:26:48 +0200 Subject: [PATCH] always observe EFIAPI calling convention when calling STO.SetAttribute We have to consider the following cases wrt. the PRINT_STATE.Output and PRINT_STATE.SetAttr EFIAPI function pointers, especially when building for x86_64 with gcc: (1) The compiler is new enough, and EFIAPI actually ensures the Microsoft calling convention. In this case everything happens to work fine even if we forget uefi_call_wrapper(), because the wrapper would expand to a normal C function call anyway. (2) Otherwise (ie. gcc is old), EFIAPI expands to nothing, and we must take into account the called function's origin: (2a) If the callee that is declared EFIAPI is *defined* inside gnu-efi, then EFIAPI means nothing for the callee too, so caller and callee only understand each other if the caller intentionally omits uefi_call_wrapper(). (2b) If the callee that is declared EFIAPI is defined by the platform UEFI implementation, then the caller *must* use uefi_call_wrapper(). The PRINT_STATE.Output EFIAPI function pointer is dereferenced correctly: the PFLUSH() distinguishes cases (2a) from (2b) by using IsLocalPrint(). However use of the PRINT_STATE.SetAttr EFIAPI function pointer is not always correct: - The PSETATTR() helper function always relies on the wrapper (case (2b)). This is correct, because PRINT_STATE.SetAttr always points to a platform-provided function. - The DbgPrint() function contains two incorrect calls: they mistakenly assume case (2a) (or case (1)), even though the pointer always points to a platform function, implying (2b). (The error is masked in case (1).) Fix them. Signed-off-by: Laszlo Ersek <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> commit ecfd1ded9a799c3a572d4eb7fbb52582fe4d3390 Author: Nigel Croxon <[email protected]> Date: Tue Jun 10 12:59:09 2014 -0400 Add VPoolPrint Function Equivalent to PoolPrint but using a va_list parameter Signed-off-by: Sylvain Chouleur <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> commit f16d93f3b9e314336a387a3885c7fd2f176c41d3 Author: Nigel Croxon <[email protected]> Date: Fri May 16 11:33:51 2014 -0400 Revert "The prototype of DbgPrint() is incorrect, at the end of "inc/efidebug.h"." A problem was found compiling on GCC 4.8. This reverts commit 644898eabc06c8efaa3aa54f84cdd468960a2f6c. commit 644898eabc06c8efaa3aa54f84cdd468960a2f6c Author: Nigel Croxon <[email protected]> Date: Wed May 14 09:09:47 2014 -0400 The prototype of DbgPrint() is incorrect, at the end of "inc/efidebug.h". Consequently, when your program calls DbgPrint() via the DEBUG() macro, it fails to set up the stack correctly (it does not pass the arguments through the ellipsis (...) according to the EFIAPI calling convention). However, va_start() inside DbgPrint() *assumes* that stack. Signed-off-by: Laszlo Ersek <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> commit 8921ba2fc5f6163bdad3b5902c5d9d638415dde0 Author: Nigel Croxon <[email protected]> Date: Mon Apr 14 18:49:23 2014 -0400 Cleaned up compile warnings. Signed-off-by: Nigel Croxon <[email protected]> commit 42cca551dbf1c0be9e02e8d3d3c417ce35749638 Author: Nigel Croxon <[email protected]> Date: Mon Apr 14 14:04:11 2014 -0400 Module lib/ParseCmdLine.c has errors, it incorrectly mixes "char" and "CHAR16" and uses a pointer to argv[] like it's argv[]. The compiler only issues warnings though. Here is a patch to remove compiler warnings and make the code behave. Signed-off-by: Bernard Burette <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> commit 4e8460f1aedd2724de876be5b154eb5752bfada5 Author: Nigel Croxon <[email protected]> Date: Mon Apr 14 13:53:03 2014 -0400 Here is a very small patch to remove a compiler warning when processing lib/smbios.c. Signed-off-by: Bernard Burette <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> commit 6a0875ca2fcb67e7d1a1e2d15f3bcc645329dc75 Author: Nigel Croxon <[email protected]> Date: Mon Apr 14 13:45:16 2014 -0400 Here is a very small patch to remove compiler warning in function "LibLocateHandleByDiskSignature()" because the "Start" variable is give a value which is not used. Signed-off-by: Bernard Burette <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> commit d5f35dfb8008ba65bcc641559accd9bc13386ef9 Author: Nigel Croxon <[email protected]> Date: Mon Apr 14 13:40:29 2014 -0400 Here is a very small patch to remove *~ files in include diretory. Signed-off-by: Bernard Burette <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> commit 1a04669a7bb022984c9b54a0f73d7d67a2540fb7 Author: Nigel Croxon <[email protected]> Date: Mon Apr 14 12:45:57 2014 -0400 Here is a patch for "DevicePathToStr()" to display device path according to UEFI 2 specification. The path is in the two files inc/efidevp.h and lib/dpath.c. It also add the Sata device path and removes the "/?" path for unknown device paths. Signed-off-by: Bernard Burette <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> commit 3c62e78556aea01e9798380cd46794c6ca09d4bd Author: Nigel Croxon <[email protected]> Date: Tue Apr 1 10:26:44 2014 -0400 Removed GPL code setjmp_ia32.S, setjmp_ia64.S, setjmp_x86_64.S Not used anymore. Signed-off-by: Nigel Croxon <[email protected]> commit f9baa4f622cf34576d73e00d4a774a31f0f81fd7 Author: Nigel Croxon <[email protected]> Date: Mon Mar 31 08:37:56 2014 -0400 Remove incumbent GPL 'debian' subdiretory. Update ChangeLog Signed-off-by: Nigel Croxon <[email protected]> Changelog format change from here and above to 'git log' style. 2014-04-01 Nigel Croxon <[email protected]> Removed GPL code setjmp_ia32.S, setjmp_ia64.S, setjmp_x86_64.S Not used anymore. Signed-off-by: Nigel Croxon <[email protected]> 2014-03-17 Nigel Croxon <[email protected]> Add support for the simple pointer and absolute pointer protocols Signed-off-by: John Cronin <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> 2014-03-14 Nigel Croxon <[email protected]> Trying to recurse into subdirectories of object files may lead to an error if the directory doesn't exist. Even when cleaning. Signed-off-by: Sylvain Gault <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> 2014-03-14 Nigel Croxon <[email protected]> Make install used to copy files unconditionnally to their destination. However, if the destination is used by another Makefile, it will always see modified files. "install" target now only updates the files when they need to. Signed-off-by: Sylvain Gault <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> 2014-02-13 Nigel Croxon <[email protected]> Patch GNU-EFI to remove the ELILO code Signed-off-by: Jerry Hoemann <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> 2014-02-13 Nigel Croxon <[email protected]> Initialize Status before calling GrowBuffer() Status must be initialized before calling GrowBuffer() as it may otherwise be uninitialized or set to EFI_BUFFER_TOO_SMALL by other functions. Signed-off-by: Gene Cumm <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> 2014-01-23 Nigel Croxon <[email protected]> These changes allow manually overridden SRCDIR (current source directory) and TOPDIR (top of source tree) to separate the build directory from the source tree. Signed-off-by: Gene Cumm <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> 2014-01-16 Nigel Croxon <[email protected]> compilation: fix uninitialized variables warning Signed-off-by: Jeremy Compostella <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> 2014-01-13 Nigel Croxon <[email protected]> Implement VSPrint function, prints a formatted unicode string to a buffer. Signed-off-by: Jeremy Compostella <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> 2014-01-10 Nigel Croxon <[email protected]> Created lib/argify.c and inc/argify.h containing the function argify. It contains verbatim copy of the comment at beginning of file from elilo. There was no COPYING file in the elilo source that the comment refers to. Signed-off-by: Jerry Hoemann <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> 2014-01-08 Nigel Croxon <[email protected]> The information needed is not really the host architecture as given by the kernel arch. The information actually needed is the default target of gcc. Signed-off-by: Sylvain Gault <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> 2013-10-11 Nigel Croxon <[email protected]> Added support for SetVariable to store volatile variable, and SetNVVariable to store non volatile variable. Signed-off-by: Sylvain Chouleur <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> 2013-10-07 Nigel Croxon <[email protected]> Atoi needs to have consistent declaration/definition. Signed-off-by: Nigel Croxon <[email protected]> 2013-10-07 Nigel Croxon <[email protected]> if you have a function that takes const arguments and then e.g. tries to copy StrCmp, gcc will give you warnings about those calls, and the warnings are right. These clutter up other things you might miss that you should be more concered about. You could work around it through vigorous typecasting to non-const types, but why should you have to? All of these functions are regorously defined as not changing their input - it is const, and should be marked as such. Signed-off-by: Peter Jones <[email protected]> 2013-10-02 Nigel Croxon <[email protected]> Added two simple applications to allocate/free memory at EFI. Used to test/find memory fragmentation issues linux. Signed-off-by: Jerry Hoemann <[email protected]> Signed-off-by: Nigel Croxon <[email protected]> 2013-06-25 Nigel Croxon <[email protected]> Sample boot service driver. Signed-off-by: David Decotigny <[email protected]> 2013-06-25 Nigel Croxon <[email protected]> Date: Tue Jun 25 08:47:03 2013 -0400 Be more pedantic when linking, don't allow duplicate symbols, abort upon first error. Also make sure linker script comes last for apps. Signed-off-by: David Decotigny <[email protected]> 2013-06-25 Nigel Croxon <[email protected]> Fix compilation on x86_64 without HAVE_USE_MS_ABI make -C apps would fail on tcc.c because uefi_call_wrapper() doesn't deal correctly with efi_callO-type invocation. Signed-off-by: David Decotigny <[email protected]> 2013-06-12 Nigel Croxon <[email protected]> Fix typo when disabling mno-mmx Signed-Off-By: Nigel Croxon <[email protected]> 2013-06-12 Nigel Croxon <[email protected]> Disable MMX and SSE GCC 4.8.0 adds some optimizations that will use movups/movaps (and use %xmm* registers) when they're faster, and of course that won't work at all since UEFI firmwares aren't guaranteed to initialize the mmx/sse instructions. This will be even more annoying, since most UEFI firmwares don't initialize the #DE or #UD trap handlers, and your backtrace will be a random path through uninitialized memory, occasionally including whatever address the IDT has for #UD, but also addresses like "0x4" and "0x507" that you don't normally expect to see in your call path. Signed-off-by: Peter Jones <[email protected]> Author: Nigel Croxon <[email protected]> Date: Wed Jun 12 10:29:40 2013 -0400 bug in make 3.82 expand to odd values Some Makefiles tickle a bug in make 3.82 that cause libefi.a and libgnuefi.a dependencies to expand to the odd values: libefi.a: boxdraw.o) smbios.o) ... libgnuefi.a(reloc_x86_64.o: The patch replaces libgnuefi.a($(OBJS)) & libefi.a($(OBJS)) with an equivalent expansion that should work with any make that supports $(patsubst). Author: Nigel Croxon <[email protected]> Date: Wed Jun 12 09:53:01 2013 -0400 support .text.* sections on x86_64 Group them in .text. Also add vague linkage sections in .text. Signed-off-by: David Decotigny <[email protected]> Author: Nigel Croxon <[email protected]> Date: Wed Jun 12 09:51:36 2013 -0400 cleanup and fix Make.defaults Reorder variables in Make.defaults so that they are grouped by functions. Also fixed ifeq (x,y) to have required syntax and make it work for ARCH amd64->x86_64 renaming on BSD. Also provides top-level Makefile with a "mkvars" target that displays effective variables. Signed-off-by: David Decotigny <[email protected]> Author: Nigel Croxon <[email protected]> Date: Wed Jun 12 09:47:16 2013 -0400 automatically determine number of uefi_call_wrapper() args on x86_64 Instead of asking developers to explicitly pass the number of parameters to the functions that get called, we determine them automatically at preprocessing time. This should result in more robust code. Argument va_num is now ignored in x86_64 code, both with and without HAVE_USE_MS_ABI. Credits to the macro magic given in the comments. Signed-off-by: David Decotigny <[email protected]> Author: Nigel Croxon <[email protected]> Date: Wed Jun 12 09:38:10 2013 -0400 fix parameter-passing corruption on x86_64 for >= 5 args On x86_64 without HAVE_USE_MS_ABI support, uefi_call_wrapper() is a variadic function. Parameters >=5 are copied to the stack and, when passed small immediate values (and possibly other parameters), gcc would emit a movl instruction before calling uefi_call_wrapper(). As a result, only the lower 32b of these stack values are significant, the upper 32b potentially contain garbage. Considering that uefi_call_wrapper() assumes these arguments are clean 64b values before calling the efi_callX() trampolines, the latter may be passed garbage. This makes calling functions like EFI_PCI_IO_PROTOCOL.Mem.Read()/Write() or BS->OpenProtocol() quite unreliable. This patch fixes this by turning uefi_call_wrapper() into a macro that allows to expose the efi_callX() trampoline signatures to the callers, so that gcc can know upfront that it has to pass all arguments to efi_callX() as clean 64b values (eg. movq for immediates). The _cast64_efi_callX macros are just here to avoid a gcc warning, they do nothing otherwise. Signed-off-by: David Decotigny <[email protected]> Author: noxorc <[email protected]> Date: Wed May 15 15:26:16 2013 -0400 - Removes the ElfW() macro usage from reloc_ia32.c and reloc_x86_64.c. These macros only exist in link.h on Linux. On FreeBSD, the equivalent macro is __ElfN(). But the macro usage is redundant. You're only going to compile the ia32 file for IA32 binaries and the x86_64 file for X64 binaries. If you had just one file built for both cases, then using the macro might make more sense. - Removes the "#define foo_t efi_foo_t" macros from reloc_ia32.c and reloc_x86_64.c. - Modifies inc/x86_64/efibind.h and inc/ia32/efibind.h to use the new definitions for uint64_t, int64_t and int8_t. The 64-bit types are now defined as: typedef int __attribute__((__mode__(__DI__))) int64_t; typedef unsigned int __attribute__((__mode__(__DI__))) uint64_t; This removes the conflict between the host types dragged in by elf.h and the type definitions in efibind.h that made the #define foo_t efi_foo_t" hack necessary. Also, int8_t is now defined as signed char instead of just char (assuming char == signed char is apparently not good enough). - Also modifies these files to use stdint.h instead of stdint-gcc.h. It's unclear if this is completely correct, but stdint-gcc.h is not present with all GCC installs, and if you use -std=c99 or later you will force this case to be hit. This also can break clang, which doesn't have a stdint-gcc.h at all. - Removes the #include of <link.h> from reloc_ia32.c and reloc_x86_64.c (since with the previous changes it's not needed anymore). - Places the #include of <elf.h> after #include <efi>/#include <efilib.h> so that we know the types will always be defined properly, in case you build on a system where <elf.h> doesn't automatically pull in the right header files to define all the needed types. (This actually happens on VxWorks. It's harmless elsewhere. If you don't care about VxWorks, you can leave this out.) - Modifies setjmp_ia32.S and setjmp_x86_64.S so to change "function" to @function. The clang compiler doesn't like the former. Clang and GCC both like the latter. - Modifles Make.defaults so that if ARCH is detected as "amd64," it's changed to "x86_64." It happens that uname -m on 64-bit FreeBSD reports the former rather than the latter, which breaks the build. This may also be the case on some other OSes. There's a way to force uname(1) to return x86_64 as the machine type, but this way is a little friendlier. - Creates gnuefi/elf_ia32_fbsd_efi.lds which specifies the object file type as elf-ia32-freebsd. This is required for building on FreeBSD/i386, not just FreeBSD/amd64. - Modifies apps/Makefile to always use $(TOPDIR)/gnuefi/elf_$(ARCH)_fbsd_efi.lds when building on either 32-bit or 64-bit FreeBSD instead of just for the x86_64 case. - Changed LDFLAGS in Make.defaults to include --no-undefined. This will cause linking to fail if there are any unsatisfied symbols when creating foo.so during any of the app builds, as opposed to just silently succeeding and producing an unusable binary. - Changed CFLAGS to include -ffreestanding -fno-stack-protector -fno-stack- check. This prevents clang from inserting a call to memset() when compiling the RtZeroMem() and RtSetMem() routines in lib/runtime/efirtlib.c and guards against the native compiler in some Linux distros from adding in stack checking code which relies on libc help that isn't present in the EFI runtime environment. This does the following: - Cleans up the ia32 and x86-64 relocation code a bit (tries to break the dependency between the host ELF headers and the EFI runtime environment) - Avoids the dependency on stdint-gcc.h which may not always be available - Allows GNU EFI to build out of the box on both FreeBSD/i386 and FreeBSD/amd64 - Allows GNU EFI to build out of the box with either GCC or clang on FreeBSD/i386 and FreeBSD/amd64 9.0 and later. - Makes things a little easier to port to VxWorks - Avoids creating un-runable binaries with unresolved symbol definitions (which can be very confusing to debug) Author: noxorc <[email protected]> Date: Wed May 8 16:29:45 2013 -0400 Add the definitions for TCP, UDP and IP, for both IPv4 and IPv6. 2013-05-02 Nigel Croxon <[email protected]> * Chnage from Matt Fleming <[email protected]> - Preparation for adding the networking protocol definitions. Add the service binding protocol. 2013-02-21 Nigel Croxon <[email protected]> * Change from Peter Jones <[email protected]> - Previously we were incorrectly passing 3 functions with the System V ABI to UEFI functions as EFI ABI functions. Mark them as EFIAPI so the compiler will (in our new GNU_EFI_USE_MS_ABI world) use the correct ABI. - These need to be EFIAPI functions because in some cases they call ST->ConOut->OutputString(), which is an EFIAPI function. (Which means that previously in cases that needed "cdecl", these didn't work right.) - If the compiler version is new enough, and GNU_EFI_USE_MS_ABI is defined, use the function attribute ms_abi on everything defined with "EFIAPI". Such calls will no longer go through efi_call*, and as such will be properly type-checked. - Honor PREFIX and LIBDIR correctly when passed in during the build. - Add machine type defines for i386, arm/thumb, ia64, ebc, x86_64. - __STDC_VERSION__ never actually gets defined unless there's a --std=... line. So we were accidentally defining lots of c99 types ourself. Since it's 2012, use --std=c11 where appropriate, and if it's defined and we're using gcc, actually include gcc's stdint definitions. - New test application added: route80h. This is a test program for PciIo. It routes ioport 80h on ICH10 to PCI. This is also useful on a very limited set of hardware to enable use of a port 80h debug card. - New test applcation added: modelist. This lists video modes the GOP driver is showing us. * Change from Finnbarr Murphy - https://sourceforge.net/p/gnu-efi/feature-requests/2/ Please add the following status codes to <efierr.h> EFI_INCOMPATIBLE_VERSION 25 EFI_SECURITY_VIOLATION 26 EFI_CRC_ERROR 27 EFI_END_OF_MEDIA 28 EFI_END_OF_FILE 31 EFI_INVALID_LANGUAGE 32 EFI_COMPROMISED_DATA 33 * Change from SourceForge.net Bug report - https://sourceforge.net/p/gnu-efi/bugs/5/ BufferSize is a UINT64 *. The file shipped with GNU EFI is from 1998 whereas the latest one is from 2004. I suspect Intel changed the API in order handle 64-bit systems. * Change from Felipe Contreras <[email protected]> - The current code seems to screw the stack at certain points. Multiple people have complained that gummiboot hangs right away, which is in part the fault of gummiboot, but happens only because the stack gets screwed. x86_64 EFI already aligns the stack, so there's no need for so much code to find a proper alignment, we always need to shift by 8 anyway. * Change from A. Steinmetz - https://sourceforge.net/p/gnu-efi/patches/1/ The patch prepares for elilo to support uefi pxe over ipv6 See uefi spec 2.3.1 errata c page 963 as reference. Verfied on an ASUS Sabertooth X79 BIOS Rev. 2104 system which is able to do an IPv6 UEFI PXE boot. * Release 3.0t 2012-09-21 Nigel Croxon <[email protected]> * Change from Peter Jones <[email protected]> - EFI Block I/O protocol versions 2 and 3 provide more information regarding physical disk layout, including alingment offset at the beginning of the disk ("LowestAlignedLba"), logical block size ("LogicalBlocksPerPhysicalBlock"), and optimal block transfer size ("OptimalTransferLengthGranularity"). * Release 3.0r 2012-04-30 Nigel Croxon <[email protected]> * Change from Matt Fleming <[email protected]> - The .reloc section is now 4096-byte boundary for x86_64. Without this patch the .reloc section will not adhere to the alignment value in the FileAlignment field (512 bytes by default) of the PE/COFF header. This results in a signed executable failing to boot in a secure boot environment. * Release 3.0q 2011-12-12 Nigel Croxon <[email protected]> * Changes from Fenghua Yu <[email protected]> - This fixes redefined types compilation failure for tcc.c on x86_64 machines. * Release 3.0p 2011-11-15 Nigel Croxon <[email protected]> * Changes from Darren Hart <[email protected]> - Conditionally assign toolchain binaries to allow overriding them. - Force a dependency on lib for gnuefi. * Release 3.0n 2011-08-23 Nigel Croxon <[email protected]> * Changes from Peter Jones <[email protected]> - Add guarantee 16-byte stack alignment on x86_64. - Add routine to make callbacks work. - Add apps/tcc.efi to test calling convention. * Release 3.0m 2011-07-22 Nigel Croxon <[email protected]> * Changed Makefiles from GPL to BSD. * Changes from Peter Jones <[email protected]> - Add ifdefs for ia64 to mirror ia32 and x86-64 so that one can build with GCC. - Add headers for PciIo. - Add the UEFI 2.x bits for EFI_BOOT_SERVICES - Add an ignore for .note.GNU-stack section in X86-64 linker maps. * Release 3.0l 2011-04-07 Nigel Croxon <[email protected]> * Change license from GPL to BSD. * Release 3.0j 2009-09-12 Julien BLACHE <[email protected]> * Add support for FreeBSD. * Release 3.0i 2009-09-11 Julien BLACHE <[email protected]> * Fix elf_ia32_efi.lds linker script to be compatible with the new linker behaviour. Patch from the RedHat bugzilla 492183. 2009-06-18 Nigel Croxon <[email protected]> * Release 3.0h 2008-11-06 Nigel Croxon <[email protected]> * Fix to not having any relocations at all. 2008-09-18 Nigel Croxon <[email protected]> * Use LIBDIR in makefiles * Add setjmp/longjmp * Fixes incorrect section attribute in crt0-efi-ia32.S * Adds value EfiResetShutdown to enum EFI_RESET_TYPE * Fixes a RAW warning in reloc_ia64.S * Adds the USB HCI device path structure in the headers patches were supplied by Peter Jones @ RedHat 2008-02-22 Nigel Croxon <[email protected]> * Added '-mno-red-zone' to x68_64 compiles. Patch provided by Mats Andersson. 2008-01-23 Nigel Croxon <[email protected]> * release 3.0e to support x86_64 EFI calling convention, the stack should be aligned in 16 bytes to make it possible to use SSE2 in EFI boot services. This patch fixes this issue. Patch provided by Huang Ying from Intel. 2007-05-11 Nigel Croxon <[email protected]> * release 3.0d to support x86_64 from Chandramouli Narayanan from Intel and based on 3.0c-1 2006-03-21 Stephane Eranian <[email protected]> * merged patch to support gcc-4.1 submitted by Raymund Will from Novell/SuSE 2006-03-20 Stephane Eranian <[email protected]> * updated ia-64 and ia-32 linker scripts to match latest gcc. The new gcc may put functions in .text* sections. patch submitted by H.J. Lu from Intel. 2004-11-19 Stephane Eranian <[email protected]> * added patch to ignore .eh_frame section for IA-32. Patch submitted by Jim Wilson 2004-09-23 Stephane Eranian <[email protected]> * added patch to discard unwind sections, newer toolchains complained about them. Patch submitted by Jesse Barnes from SGI. 2003-09-29 Stephane Eranian <[email protected]> * updated elf_ia64_efi.lds to reflect new data sections created by gcc-3.3. Patch provided by Andreas Schwab from Suse. 2003-06-20 Stephane Eranian <[email protected]> * updated elf_ia64_efi.lds and elf_ia32_efi.lds to include new types data sections produced by recent version of gcc-3.x 2002-02-22 Stephane Eranian <[email protected]> * release 3.0a * modified both IA-64 and IA-32 loader scripts to add support for the new .rodata sections names (such as rodata.str2.8). Required for new versions of gcc3.x. 2001-06-20 Stephane Eranian <[email protected]> * release 3.0 * split gnu-efi package in two different packages: the libary+include+crt and the bootloader. * removed W2U() hack and related files to get from wide-char to unicode. * Use -fshort-wchar option for unicode. * restructured Makefiles now install under INSTALLROOT. 2001-04-06 Stephane Eranian <[email protected]> * incorporated patches from David and Michael Johnston at Intel to get the package to compile for IA-32 linux target. * Fixed ELILO to compile for Ia-32 (does not execute yet, though): Makefile and start_kernel() function. 2001-04-06 Andreas Schwab <[email protected]> * Fixed config.c to get the timeout directive to do something. implemented the global root= directive. * Fix the efi_main() to deal with the -C option properly 2001-04-05 Stephane Eranian <[email protected]> * update efi library to latest EFI toolkit 1.02 as distributed by Intel. Fixed header + library files to compile with GCC * merged ELI and LILO (as of gnu-efi-1.1) together, mostly taking the config file feature of ELI. * renamed LILO to ELILO to make the distinction * restructured code to make it easier to understand and maintain * fixed FPSWA driver checking and loading: we try all possible files and let the driver itself figure out if it is the most recent. * added support for compression (gzip) but keep support for plain ELF image. ELILO autodetects the format * change the way the kernel is invoked. Now we call it in physical memory mode. This breaks the dependency between the kernel code and the loader. No more lilo_start.c madness. * changed the way the boot_params are passed. We don't use the ZERO_PAGE_ADDR trick anymore. Instead we use EFI runtime memory. The address of the structure is passed to the kernel in r28 by our convention. * released as gnu-efi-2.0 2001-04-03 David Mosberger <[email protected]> * gnuefi/reloc_ia32.c (_relocate): Change return type from "void" to "int". Return error status if relocation fails for some reason. * gnuefi/elf_ia32_efi.lds: Drop unneeded ".rel.reloc" section. * gnuefi/crt0-efi-ia32.S (_start): Exit if _relocate() returns with non-zero exit status. * inc/ia32/efibind.h [__GNUC__]: Force 8-byte alignment for 64-bit types as that is what EFI appears to be expecting, despite the "#pragma pack()" at the beginning of the file! 2001-03-29 David Mosberger <[email protected]> * gnuefi/reloc_ia32.c: Add a couple of defines to work around libc/efilib collision on uint64_t et al. (_relocate): Use ELF32_R_TYPE() instead of ELFW(R_TYPE)(). * gnuefi/crt0-efi-ia32.S (dummy): Add a dummy relocation entry. 2001-03-29 David Mosberger <[email protected]> * gnuefi/reloc_ia32.c: Add a couple of defines to work around libc/efilib collision on uint64_t et al. (_relocate): Use ELF32_R_TYPE() instead of ELFW(R_TYPE)(). * gnuefi/crt0-efi-ia32.S (dummy): Add a dummy relocation entry. 2000-10-26 David Mosberger <[email protected]> * gnuefi/elf_ia64_efi.lds: Mention .rela.sdata. * Make.defaults (CFLAGS): Remove -nostdinc flags so we can pick up the C compiler's stdarg.h. * inc/stdarg.h: Remove this file. It's not correct for gcc (nor most other optimizing compilers). 2000-10-10 Stephane Eranian <[email protected]> * cleaned up the error message and printing of those. * added support to load the FPSWA from a file in case support is not present in the firmware already * fixed split_args() to do the right thing when you have leading spaces before kernel name * changed the argify() function to rely on \0 instead of LoadOptionSize as the field seems to be broken with current firmware * bumped version to 1.0 2000-10-04 David Mosberger <[email protected]> * gnuefi/reloc_ia64.S: Reserve space for up to 750 function descriptors. * gnuefi/elf_ia64_efi.lds: Add .sdata section for small data and put __gp in the "middle" of it. * gnuefi/crt0-efi-ia64.S (_start): Use movl/add to load gp-relative addresses that could be out of the range of the addl offset. * gnuefi/reloc_ia64.S (_relocate): Ditto. * apps/Makefile: Remove standard rules and include Make.rules instead. * lilo/Makefile: Ditto. * Make.rules: New file. 2000-08-04 Stephane Eranian <[email protected]> * released version 0.9 * incorporated ACPI changes for Asuza by NEC < [email protected]> * added support for initrd (-i option) original ELI code from Bill Nottingham <[email protected]>) * lots of cleanups * got rid of #ifdef LILO_DEBUG and uses macro instead * fix a few extra memory leaks in create_boot_params() * added exit capability just before starting the kernel 2000-06-22 David Mosberger <[email protected]> * gnuefi/elf_ia64_efi.lds: Add .srodata, .ctors, .IA64.unwind, .IA64.unwind_info to .data section and .rela.ctors to .rela section. 2000-04-03 David Mosberger <[email protected]> * lilo/lilo.c (LILO_VERSION): Up version number to 0.9. * gnuefi/elf_ia64_efi.lds: Include .IA_64.unwind and .IA_64.unwind_info in .data segment to avoid EFI load error "ImageAddress: pointer outside of image" error due to the .dynsym relocations against these sections. * ChangeLog: Moved from lilo/ChangeLogs. * gnuefi/reloc_ia64.S: fixed typo: .space directive had constant 100 hardcoded instead of using MAX_FUNCTION_DESCRIPTORS macro. Duh. 2000-03-17 Stephane Eranian <[email protected]> * Released 0.8 * replace the getopt.c with new version free with better license * created a documentation file * fix a couple of memory leaks * code cleanups * created a separate directory for lilo in the gnu-efi package. * added support for the BOOT_IMAGE argument to kernel * default is to build natively now
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
# -*- makefile -*- # Copyright (c) 1999-2007 Hewlett-Packard Development Company, L.P. # Contributed by David Mosberger <[email protected]> # Contributed by Stephane Eranian <[email protected]> # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials # provided with the distribution. # * Neither the name of Hewlett-Packard Co. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND # CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, # INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS # BE LIABLE FOR ANYDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, # OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF # THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # TOPDIR := $(shell if [ "$$PWD" != "" ]; then echo $$PWD; else pwd; fi) # # Variables below overridable from command-line: # make VARNAME=value ... # # # Where to install the package. GNU-EFI will create and access # lib and include under the root # INSTALLROOT := / PREFIX := /usr/local LIBDIR := $(PREFIX)/lib INSTALL := install # Compilation tools HOSTCC := $(prefix)gcc CC := $(prefix)$(CROSS_COMPILE)gcc AS := $(prefix)$(CROSS_COMPILE)as LD := $(prefix)$(CROSS_COMPILE)ld AR := $(prefix)$(CROSS_COMPILE)ar RANLIB := $(prefix)$(CROSS_COMPILE)ranlib OBJCOPY := $(prefix)$(CROSS_COMPILE)objcopy # Host/target identification OS := $(shell uname -s) HOSTARCH ?= $(shell $(HOSTCC) -dumpmachine | cut -f1 -d- | sed -e s,i[3456789]86,ia32, -e 's,armv[67].*,arm,' ) ARCH ?= $(shell $(HOSTCC) -dumpmachine | cut -f1 -d- | sed -e s,i[3456789]86,ia32, -e 's,armv[67].*,arm,' ) # Get ARCH from the compiler if cross compiling ifneq ($(CROSS_COMPILE),) override ARCH := $(shell $(CC) -dumpmachine | cut -f1 -d-| sed -e s,i[3456789]86,ia32, -e 's,armv[67].*,arm,' ) endif # FreeBSD (and possibly others) reports amd64 instead of x86_64 ifeq ($(ARCH),amd64) override ARCH := x86_64 endif # # Where to build the package # OBJDIR := $(TOPDIR)/$(ARCH) # # Variables below derived from variables above # # Arch-specific compilation flags CPPFLAGS += -DCONFIG_$(ARCH) CFLAGS += -Wno-error=pragmas ifeq ($(ARCH),ia64) CFLAGS += -mfixed-range=f32-f127 endif ifeq ($(ARCH),ia32) CFLAGS += -mno-mmx -mno-sse ifeq ($(HOSTARCH),x86_64) ARCH3264 = -m32 endif endif ifeq ($(ARCH),x86_64) GCCVERSION := $(shell $(CC) -dumpversion | cut -f1 -d.) GCCMINOR := $(shell $(CC) -dumpversion | cut -f2 -d.) USING_CLANG := $(shell $(CC) -v 2>&1 | grep -q 'clang version' && echo clang) # Rely on GCC MS ABI support? GCCNEWENOUGH := $(shell ( [ $(GCCVERSION) -gt "4" ] \ || ( [ $(GCCVERSION) -eq "4" ] \ && [ $(GCCMINOR) -ge "7" ] ) ) \ && echo 1) ifeq ($(GCCNEWENOUGH),1) CPPFLAGS += -DGNU_EFI_USE_MS_ABI -maccumulate-outgoing-args --std=c11 else ifeq ($(USING_CLANG),clang) CPPFLAGS += -DGNU_EFI_USE_MS_ABI --std=c11 endif CFLAGS += -mno-red-zone ifeq ($(HOSTARCH),ia32) ARCH3264 = -m64 endif endif ifneq (,$(filter $(ARCH),ia32 x86_64)) # Disable AVX, if the compiler supports that. CC_CAN_DISABLE_AVX=$(shell $(CC) -Werror -c -o /dev/null -xc -mno-avx - </dev/null >/dev/null 2>&1 && echo 1) ifeq ($(CC_CAN_DISABLE_AVX), 1) CFLAGS += -mno-avx endif endif ifeq ($(ARCH),mips64el) CFLAGS += -march=mips64r2 ARCH3264 = -mabi=64 endif # # Set HAVE_EFI_OBJCOPY if objcopy understands --target efi-[app|bsdrv|rtdrv], # otherwise we need to compose the PE/COFF header using the assembler # ifneq ($(ARCH),aarch64) ifneq ($(ARCH),arm) ifneq ($(ARCH),mips64el) export HAVE_EFI_OBJCOPY=y endif endif endif ifneq ($(ARCH),arm) export LIBGCC=$(shell $(CC) $(ARCH3264) -print-libgcc-file-name) endif ifeq ($(ARCH),arm) CFLAGS += -marm endif # Generic compilation flags INCDIR += -I$(SRCDIR) -I$(TOPDIR)/inc -I$(TOPDIR)/inc/$(ARCH) \ -I$(TOPDIR)/inc/protocol # Only enable -fpic for non MinGW compilers (unneeded on MinGW) GCCMACHINE := $(shell $(CC) -dumpmachine) ifneq (mingw32,$(findstring mingw32, $(GCCMACHINE))) CFLAGS += -fpic endif ifeq (FreeBSD, $(findstring FreeBSD, $(OS))) CFLAGS += $(ARCH3264) -g -O2 -Wall -Wextra -Werror \ -fshort-wchar -fno-strict-aliasing \ -ffreestanding -fno-stack-protector else CFLAGS += $(ARCH3264) -g -O2 -Wall -Wextra -Werror \ -fshort-wchar -fno-strict-aliasing \ -ffreestanding -fno-stack-protector -fno-stack-check \ -fno-stack-check \ $(if $(findstring gcc,$(CC)),-fno-merge-all-constants,) endif ARFLAGS := rDv ASFLAGS += $(ARCH3264) LDFLAGS += -nostdlib --warn-common --no-undefined --fatal-warnings \ --build-id=sha1
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
------------------------------------------------- Building EFI Applications Using the GNU Toolchain ------------------------------------------------- David Mosberger <[email protected]> 23 September 1999 Copyright (c) 1999-2007 Hewlett-Packard Co. Copyright (c) 2006-2010 Intel Co. Last update: 04/09/2007 * Introduction This document has two parts: the first part describes how to develop EFI applications for IA-64,x86 and x86_64 using the GNU toolchain and the EFI development environment contained in this directory. The second part describes some of the more subtle aspects of how this development environment works. * Part 1: Developing EFI Applications ** Prerequisites: To develop x86 and x86_64 EFI applications, the following tools are needed: - gcc-3.0 or newer (gcc 2.7.2 is NOT sufficient!) As of gnu-efi-3.0b, the Redhat 8.0 toolchain is known to work, but the Redhat 9.0 toolchain is not currently supported. - A version of "objcopy" that supports EFI applications. To check if your version includes EFI support, issue the command: objcopy --help Verify that the line "supported targets" contains the string "efi-app-ia32" and "efi-app-x86_64" and that the "-j" option accepts wildcards. The binutils release binutils-2.24 supports Intel64 EFI and accepts wildcard section names. - For debugging purposes, it's useful to have a version of "objdump" that supports EFI applications as well. This allows inspect and disassemble EFI binaries. To develop IA-64 EFI applications, the following tools are needed: - A version of gcc newer than July 30th 1999 (older versions had problems with generating position independent code). As of gnu-efi-3.0b, gcc-3.1 is known to work well. - A version of "objcopy" that supports EFI applications. To check if your version includes EFI support, issue the command: objcopy --help Verify that the line "supported targets" contains the string "efi-app-ia64" and that the "-j" option accepts wildcards. - For debugging purposes, it's useful to have a version of "objdump" that supports EFI applications as well. This allows inspect and disassemble EFI binaries. ** Directory Structure This EFI development environment contains the following subdirectories: inc: This directory contains the EFI-related include files. The files are taken from Intel's EFI source distribution, except that various fixes were applied to make it compile with the GNU toolchain. lib: This directory contains the source code for Intel's EFI library. Again, the files are taken from Intel's EFI source distribution, with changes to make them compile with the GNU toolchain. gnuefi: This directory contains the glue necessary to convert ELF64 binaries to EFI binaries. Various runtime code bits, such as a self-relocator are included as well. This code has been contributed by the Hewlett-Packard Company and is distributed under the GNU GPL. apps: This directory contains a few simple EFI test apps. ** Setup It is necessary to edit the Makefile in the directory containing this README file before EFI applications can be built. Specifically, you should verify that macros CC, AS, LD, AR, RANLIB, and OBJCOPY point to the appropriate compiler, assembler, linker, ar, and ranlib binaries, respectively. If you're working in a cross-development environment, be sure to set macro ARCH to the desired target architecture ("ia32" for x86, "x86_64" for x86_64 and "ia64" for IA-64). For convenience, this can also be done from the make command line (e.g., "make ARCH=ia64"). ** Building To build the sample EFI applications provided in subdirectory "apps", simply invoke "make" in the toplevel directory (the directory containing this README file). This should build lib/libefi.a and gnuefi/libgnuefi.a first and then all the EFI applications such as a apps/t6.efi. ** Running Just copy the EFI application (e.g., apps/t6.efi) to the EFI filesystem, boot EFI, and then select "Invoke EFI application" to run the application you want to test. Alternatively, you can invoke the Intel-provided "nshell" application and then invoke your test binary via the command line interface that "nshell" provides. ** Writing Your Own EFI Application Suppose you have your own EFI application in a file called "apps/myefiapp.c". To get this application built by the GNU EFI build environment, simply add "myefiapp.efi" to macro TARGETS in apps/Makefile. Once this is done, invoke "make" in the top level directory. This should result in EFI application apps/myefiapp.efi, ready for execution. The GNU EFI build environment allows to write EFI applications as described in Intel's EFI documentation, except for two differences: - The EFI application's entry point is always called "efi_main". The declaration of this routine is: EFI_STATUS efi_main (EFI_HANDLE image, EFI_SYSTEM_TABLE *systab); - UNICODE string literals must be written as W2U(L"Sample String") instead of just L"Sample String". The W2U() macro is defined in <efilib.h>. This header file also declares the function W2UCpy() which allows to convert a wide string into a UNICODE string and store the result in a programmer-supplied buffer. - Calls to EFI services should be made via uefi_call_wrapper(). This ensures appropriate parameter passing for the architecture. * Part 2: Inner Workings WARNING: This part contains all the gory detail of how the GNU EFI toolchain works. Normal users do not have to worry about such details. Reading this part incurs a definite risk of inducing severe headaches or other maladies. The basic idea behind the GNU EFI build environment is to use the GNU toolchain to build a normal ELF binary that, at the end, is converted to an EFI binary. EFI binaries are really just PE32+ binaries. PE stands for "Portable Executable" and is the object file format Microsoft is using on its Windows platforms. PE is basically the COFF object file format with an MS-DOS2.0 compatible header slapped on in front of it. The "32" in PE32+ stands for 32 bits, meaning that PE32 is a 32-bit object file format. The plus in "PE32+" indicates that this format has been hacked to allow loading a 4GB binary anywhere in a 64-bit address space (unlike ELF64, however, this is not a full 64-bit object file format because the entire binary cannot span more than 4GB of address space). EFI binaries are plain PE32+ binaries except that the "subsystem id" differs from normal Windows binaries. There are two flavors of EFI binaries: "applications" and "drivers" and each has there own subsystem id and are identical otherwise. At present, the GNU EFI build environment supports the building of EFI applications only, though it would be trivial to generate drivers, as the only difference is the subsystem id. For more details on PE32+, see the spec at http://msdn.microsoft.com/library/specs/msdn_pecoff.htm. In theory, converting a suitable ELF64 binary to PE32+ is easy and could be accomplished with the "objcopy" utility by specifying option --target=efi-app-ia32 (x86) or --target=efi-app-ia64 (IA-64). But life never is that easy, so here some complicating factors: (1) COFF sections are very different from ELF sections. ELF binaries distinguish between program headers and sections. The program headers describe the memory segments that need to be loaded/initialized, whereas the sections describe what constitutes those segments. In COFF (and therefore PE32+) no such distinction is made. Thus, COFF sections need to be page aligned and have a size that is a multiple of the page size (4KB for EFI), whereas ELF allows sections at arbitrary addresses and with arbitrary sizes. (2) EFI binaries should be relocatable. Since EFI binaries are executed in physical mode, EFI cannot guarantee that a given binary can be loaded at its preferred address. EFI does _try_ to load a binary at it's preferred address, but if it can't do so, it will load it at another address and then relocate the binary using the contents of the .reloc section. (3) On IA-64, the EFI entry point needs to point to a function descriptor, not to the code address of the entry point. (4) The EFI specification assumes that wide characters use UNICODE encoding. ANSI C does not specify the size or encoding that a wide character uses. These choices are "implementation defined". On most UNIX systems, the GNU toolchain uses a wchar_t that is 4 bytes in size. The encoding used for such characters is (mostly) UCS4. In the following sections, we address how the GNU EFI build environment addresses each of these issues. ** (1) Accommodating COFF Sections In order to satisfy the COFF constraint of page-sized and page-aligned sections, the GNU EFI build environment uses the special linker script in gnuefi/elf_$(ARCH)_efi.lds where $(ARCH) is the target architecture ("ia32" for x86, "x86_64" for x86_64 and "ia64" for IA-64). This script is set up to create only eight COFF section, each page aligned and page sized.These eight sections are used to group together the much greater number of sections that are typically present in ELF object files. Specifically: .hash (and/or .gnu.hash) Collects the ELF .hash info (this section _must_ be the first section in order to build a shared object file; the section is not actually loaded or used at runtime). GNU binutils provides a mechanism to generate different hash info via --hash-style=<sysv|gnu|both> option. In this case output shared object will contain .hash section, .gnu.hash section or both. In order to generate correct output linker script preserves both types of hash sections. .text Collects all sections containing executable code. .data Collects read-only and read-write data, literal string data, global offset tables, the uninitialized data segment (bss) and various other sections containing data. The reason read-only data is placed here instead of the in .text is to make it possible to disassemble the .text section without getting garbage due to read-only data. Besides, since EFI binaries execute in physical mode, differences in page protection do not matter. The reason the uninitialized data is placed in this section is that the EFI loader appears to be unable to handle sections that are allocated but not loaded from the binary. .dynamic, .dynsym, .rela, .rel, .reloc These sections contains the dynamic information necessary to self-relocate the binary (see below). A couple of more points worth noting about the linker script: o On IA-64, the global pointer symbol (__gp) needs to be placed such that the _entire_ EFI binary can be addressed using the signed 22-bit offset that the "addl" instruction affords. Specifically, this means that __gp should be placed at ImageBase + 0x200000. Strictly speaking, only a couple of symbols need to be addressable in this fashion, so with some care it should be possible to build binaries much larger than 4MB. To get a list of symbols that need to be addressable in this fashion, grep the assembly files in directory gnuefi for the string "@gprel". o The link address (ImageBase) of the binary is (arbitrarily) set to zero. This could be set to something larger to increase the chance of EFI being able to load the binary without requiring relocation. However, a start address of 0 makes debugging a wee bit easier (great for those of us who can add, but not subtract... ;-). o The relocation related sections (.dynamic, .rel, .rela, .reloc) cannot be placed inside .data because some tools in the GNU toolchain rely on the existence of these sections. o Some sections in the ELF binary intentionally get dropped when building the EFI binary. Particularly noteworthy are the dynamic relocation sections for the .plabel and .reloc sections. It would be _wrong_ to include these sections in the EFI binary because it would result in .reloc and .plabel being relocated twice (once by the EFI loader and once by the self-relocator; see below for a description of the latter). Specifically, only the sections mentioned with the -j option in the final "objcopy" command are retained in the EFI binary (see Make.rules). ** (2) Building Relocatable Binaries ELF binaries are normally linked for a fixed load address and are thus not relocatable. The only kind of ELF object that is relocatable are shared objects ("shared libraries"). However, even those objects are usually not completely position independent and therefore require runtime relocation by the dynamic loader. For example, IA-64 binaries normally require relocation of the global offset table. The approach to building relocatable binaries in the GNU EFI build environment is to: (a) build an ELF shared object (b) link it together with a self-relocator that takes care of applying the dynamic relocations that may be present in the ELF shared object (c) convert the resulting image to an EFI binary The self-relocator is of course architecture dependent. The x86 version can be found in gnuefi/reloc_ia32.c, the x86_64 version can be found in gnuefi/reloc_x86_64.c and the IA-64 version can be found in gnuefi/reloc_ia64.S. The self-relocator operates as follows: the startup code invokes it right after EFI has handed off control to the EFI binary at symbol "_start". Upon activation, the self-relocator searches the .dynamic section (whose starting address is given by symbol _DYNAMIC) for the dynamic relocation information, which can be found in the DT_REL, DT_RELSZ, and DT_RELENT entries of the dynamic table (DT_RELA, DT_RELASZ, and DT_RELAENT in the case of rela relocations, as is the case for IA-64). The dynamic relocation information points to the ELF relocation table. Once this table is found, the self-relocator walks through it, applying each relocation one by one. Since the EFI binaries are fully resolved shared objects, only a subset of all possible relocations need to be supported. Specifically, on x86 only the R_386_RELATIVE relocation is needed. On IA-64, the relocations R_IA64_DIR64LSB, R_IA64_REL64LSB, and R_IA64_FPTR64LSB are needed. Note that the R_IA64_FPTR64LSB relocation requires access to the dynamic symbol table. This is why the .dynsym section is included in the EFI binary. Another complication is that this relocation requires memory to hold the function descriptors (aka "procedure labels" or "plabels"). Each function descriptor uses 16 bytes of memory. The IA-64 self-relocator currently reserves a static memory area that can hold 100 of these descriptors. If the self-relocator runs out of space, it causes the EFI binary to fail with error code 5 (EFI_BUFFER_TOO_SMALL). When this happens, the manifest constant MAX_FUNCTION_DESCRIPTORS in gnuefi/reloc_ia64.S should be increased and the application recompiled. An easy way to count the number of function descriptors required by an EFI application is to run the command: objdump --dynamic-reloc example.so | fgrep FPTR64 | wc -l assuming "example" is the name of the desired EFI application. ** (3) Creating the Function Descriptor for the IA-64 EFI Binaries As mentioned above, the IA-64 PE32+ format assumes that the entry point of the binary is a function descriptor. A function descriptors consists of two double words: the first one is the code entry point and the second is the global pointer that should be loaded before calling the entry point. Since the ELF toolchain doesn't know how to generate a function descriptor for the entry point, the startup code in gnuefi/crt0-efi-ia64.S crafts one manually by with the code: .section .plabel, "a" _start_plabel: data8 _start data8 __gp this places the procedure label for entry point _start in a section called ".plabel". Now, the only problem is that _start and __gp need to be relocated _before_ EFI hands control over to the EFI binary. Fortunately, PE32+ defines a section called ".reloc" that can achieve this. Thus, in addition to manually crafting the function descriptor, the startup code also crafts a ".reloc" section that has will cause the EFI loader to relocate the function descriptor before handing over control to the EFI binary (again, see the PECOFF spec mentioned above for details). A final question may be why .plabel and .reloc need to go in their own COFF sections. The answer is simply: we need to be able to discard the relocation entries that are generated for these sections. By placing them in these sections, the relocations end up in sections ".rela.plabel" and ".rela.reloc" which makes it easy to filter them out in the filter script. Also, the ".reloc" section needs to be in its own section so that the objcopy program can recognize it and can create the correct directory entries in the PE32+ binary. ** (4) Convenient and Portable Generation of UNICODE String Literals As of gnu-efi-3.0, we make use (and somewhat abuse) the gcc option that forces wide characters (WCHAR_T) to use short integers (2 bytes) instead of integers (4 bytes). This way we match the Unicode character size. By abuse, we mean that we rely on the fact that the regular ASCII characters are encoded the same way between (short) wide characters and Unicode and basically only use the first byte. This allows us to just use them interchangeably. The gcc option to force short wide characters is : -fshort-wchar * * * The End * * *
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
/* Same as elf_x86_64_fbsd_efi.lds, except for OUTPUT_FORMAT below - KEEP IN SYNC */ OUTPUT_FORMAT("elf64-x86-64", "elf64-x86-64", "elf64-x86-64") OUTPUT_ARCH(i386:x86-64) ENTRY(_start) SECTIONS { . = 0; ImageBase = .; /* .hash and/or .gnu.hash MUST come first! */ .hash : { *(.hash) } .gnu.hash : { *(.gnu.hash) } . = ALIGN(4096); .eh_frame : { *(.eh_frame) } . = ALIGN(4096); .text : { _text = .; *(.text) *(.text.*) *(.gnu.linkonce.t.*) . = ALIGN(16); } _etext = .; _text_size = . - _text; . = ALIGN(4096); .reloc : { *(.reloc) } . = ALIGN(4096); .data : { _data = .; *(.rodata*) *(.got.plt) *(.got) *(.data*) *(.sdata) /* the EFI loader doesn't seem to like a .bss section, so we stick it all into .data: */ *(.sbss) *(.scommon) *(.dynbss) *(.bss) *(COMMON) *(.rel.local) } .note.gnu.build-id : { *(.note.gnu.build-id) } _edata = .; _data_size = . - _etext; . = ALIGN(4096); .dynamic : { *(.dynamic) } . = ALIGN(4096); .rela : { *(.rela.data*) *(.rela.got) *(.rela.stab) } . = ALIGN(4096); .dynsym : { *(.dynsym) } . = ALIGN(4096); .dynstr : { *(.dynstr) } . = ALIGN(4096); .ignored.reloc : { *(.rela.reloc) *(.eh_frame) *(.note.GNU-stack) } .comment 0 : { *(.comment) } }
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
OUTPUT_FORMAT("elf64-littleaarch64", "elf64-littleaarch64", "elf64-littleaarch64") OUTPUT_ARCH(aarch64) ENTRY(_start) SECTIONS { .text 0x0 : { _text = .; *(.text.head) *(.text) *(.text.*) *(.gnu.linkonce.t.*) *(.srodata) *(.rodata*) . = ALIGN(16); } _etext = .; _text_size = . - _text; .dynamic : { *(.dynamic) } .data : ALIGN(4096) { _data = .; *(.sdata) *(.data) *(.data1) *(.data.*) *(.got.plt) *(.got) /* the EFI loader doesn't seem to like a .bss section, so we stick it all into .data: */ . = ALIGN(16); _bss = .; *(.sbss) *(.scommon) *(.dynbss) *(.bss) *(COMMON) . = ALIGN(16); _bss_end = .; } .rela.dyn : { *(.rela.dyn) } .rela.plt : { *(.rela.plt) } .rela.got : { *(.rela.got) } .rela.data : { *(.rela.data) *(.rela.data*) } . = ALIGN(512); _edata = .; _data_size = . - _data; . = ALIGN(4096); .dynsym : { *(.dynsym) } . = ALIGN(4096); .dynstr : { *(.dynstr) } . = ALIGN(4096); .note.gnu.build-id : { *(.note.gnu.build-id) } /DISCARD/ : { *(.rel.reloc) *(.eh_frame) *(.note.GNU-stack) } .comment 0 : { *(.comment) } }
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
/* reloc_ia32.c - position independent x86 ELF shared object relocator Copyright (C) 1999 Hewlett-Packard Co. Contributed by David Mosberger <[email protected]>. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Hewlett-Packard Co. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANYDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <efi.h> #include <efilib.h> #include <elf.h> EFI_STATUS _relocate (long ldbase, Elf32_Dyn *dyn, EFI_HANDLE image EFI_UNUSED, EFI_SYSTEM_TABLE *systab EFI_UNUSED) { long relsz = 0, relent = 0; Elf32_Rel *rel = 0; unsigned long *addr; int i; for (i = 0; dyn[i].d_tag != DT_NULL; ++i) { switch (dyn[i].d_tag) { case DT_REL: rel = (Elf32_Rel*) ((unsigned long)dyn[i].d_un.d_ptr + ldbase); break; case DT_RELSZ: relsz = dyn[i].d_un.d_val; break; case DT_RELENT: relent = dyn[i].d_un.d_val; break; case DT_RELA: break; default: break; } } if (!rel && relent == 0) return EFI_SUCCESS; if (!rel || relent == 0) return EFI_LOAD_ERROR; while (relsz > 0) { /* apply the relocs */ switch (ELF32_R_TYPE (rel->r_info)) { case R_386_NONE: break; case R_386_RELATIVE: addr = (unsigned long *) (ldbase + rel->r_offset); *addr += ldbase; break; default: break; } rel = (Elf32_Rel*) ((char *) rel + relent); relsz -= relent; } return EFI_SUCCESS; }
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
/* reloc_arm.c - position independent x86 ELF shared object relocator Copyright (C) 2014 Linaro Ltd. <[email protected]> Copyright (C) 1999 Hewlett-Packard Co. Contributed by David Mosberger <[email protected]>. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Hewlett-Packard Co. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANYDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <efi.h> #include <efilib.h> #include <elf.h> EFI_STATUS _relocate (long ldbase, Elf32_Dyn *dyn, EFI_HANDLE image EFI_UNUSED, EFI_SYSTEM_TABLE *systab EFI_UNUSED) { long relsz = 0, relent = 0; Elf32_Rel *rel = 0; unsigned long *addr; int i; for (i = 0; dyn[i].d_tag != DT_NULL; ++i) { switch (dyn[i].d_tag) { case DT_REL: rel = (Elf32_Rel*) ((unsigned long)dyn[i].d_un.d_ptr + ldbase); break; case DT_RELSZ: relsz = dyn[i].d_un.d_val; break; case DT_RELENT: relent = dyn[i].d_un.d_val; break; default: break; } } if (!rel && relent == 0) return EFI_SUCCESS; if (!rel || relent == 0) return EFI_LOAD_ERROR; while (relsz > 0) { /* apply the relocs */ switch (ELF32_R_TYPE (rel->r_info)) { case R_ARM_NONE: break; case R_ARM_RELATIVE: addr = (unsigned long *) (ldbase + rel->r_offset); *addr += ldbase; break; default: break; } rel = (Elf32_Rel*) ((char *) rel + relent); relsz -= relent; } return EFI_SUCCESS; }
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
/* reloc_x86_64.c - position independent x86_64 ELF shared object relocator Copyright (C) 1999 Hewlett-Packard Co. Contributed by David Mosberger <[email protected]>. Copyright (C) 2005 Intel Co. Contributed by Fenghua Yu <[email protected]>. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Hewlett-Packard Co. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANYDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <efi.h> #include <efilib.h> #include <elf.h> EFI_STATUS _relocate (long ldbase, Elf64_Dyn *dyn, EFI_HANDLE image EFI_UNUSED, EFI_SYSTEM_TABLE *systab EFI_UNUSED) { long relsz = 0, relent = 0; Elf64_Rel *rel = 0; unsigned long *addr; int i; for (i = 0; dyn[i].d_tag != DT_NULL; ++i) { switch (dyn[i].d_tag) { case DT_RELA: rel = (Elf64_Rel*) ((unsigned long)dyn[i].d_un.d_ptr + ldbase); break; case DT_RELASZ: relsz = dyn[i].d_un.d_val; break; case DT_RELAENT: relent = dyn[i].d_un.d_val; break; default: break; } } if (!rel && relent == 0) return EFI_SUCCESS; if (!rel || relent == 0) return EFI_LOAD_ERROR; while (relsz > 0) { /* apply the relocs */ switch (ELF64_R_TYPE (rel->r_info)) { case R_X86_64_NONE: break; case R_X86_64_RELATIVE: addr = (unsigned long *) (ldbase + rel->r_offset); *addr += ldbase; break; default: break; } rel = (Elf64_Rel*) ((char *) rel + relent); relsz -= relent; } return EFI_SUCCESS; }
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
OUTPUT_FORMAT("elf32-i386", "elf32-i386", "elf32-i386") OUTPUT_ARCH(i386) ENTRY(_start) SECTIONS { . = 0; ImageBase = .; /* .hash and/or .gnu.hash MUST come first! */ .hash : { *(.hash) } .gnu.hash : { *(.gnu.hash) } . = ALIGN(4096); .text : { _text = .; *(.text) *(.text.*) *(.gnu.linkonce.t.*) . = ALIGN(16); } _etext = .; _text_size = . - _text; . = ALIGN(4096); .sdata : { _data = .; *(.got.plt) *(.got) *(.srodata) *(.sdata) *(.sbss) *(.scommon) } . = ALIGN(4096); .data : { *(.rodata*) *(.data) *(.data1) *(.data.*) *(.sdata) *(.got.plt) *(.got) /* the EFI loader doesn't seem to like a .bss section, so we stick it all into .data: */ *(.sbss) *(.scommon) *(.dynbss) *(.bss) *(COMMON) } .note.gnu.build-id : { *(.note.gnu.build-id) } . = ALIGN(4096); .dynamic : { *(.dynamic) } . = ALIGN(4096); .rel : { *(.rel.data) *(.rel.data.*) *(.rel.got) *(.rel.stab) *(.data.rel.ro.local) *(.data.rel.local) *(.data.rel.ro) *(.data.rel*) } _edata = .; _data_size = . - _etext; . = ALIGN(4096); .reloc : /* This is the PECOFF .reloc section! */ { *(.reloc) } . = ALIGN(4096); .dynsym : { *(.dynsym) } . = ALIGN(4096); .dynstr : { *(.dynstr) } . = ALIGN(4096); /DISCARD/ : { *(.rel.reloc) *(.eh_frame) *(.note.GNU-stack) } .comment 0 : { *(.comment) } }
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
/* * crt0-efi-arm.S - PE/COFF header for ARM EFI applications * * Copright (C) 2014 Linaro Ltd. <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice and this list of conditions, without modification. * 2. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * Alternatively, this software may be distributed under the terms of the * GNU General Public License as published by the Free Software Foundation; * either version 2 of the License, or (at your option) any later version. */ .section .text.head /* * Magic "MZ" signature for PE/COFF */ .globl ImageBase ImageBase: .ascii "MZ" .skip 58 // 'MZ' + pad + offset == 64 .long pe_header - ImageBase // Offset to the PE header. pe_header: .ascii "PE" .short 0 coff_header: .short 0x1c2 // Mixed ARM/Thumb .short 2 // nr_sections .long 0 // TimeDateStamp .long 0 // PointerToSymbolTable .long 1 // NumberOfSymbols .short section_table - optional_header // SizeOfOptionalHeader .short 0x306 // Characteristics. // IMAGE_FILE_32BIT_MACHINE | // IMAGE_FILE_DEBUG_STRIPPED | // IMAGE_FILE_EXECUTABLE_IMAGE | // IMAGE_FILE_LINE_NUMS_STRIPPED optional_header: .short 0x10b // PE32+ format .byte 0x02 // MajorLinkerVersion .byte 0x14 // MinorLinkerVersion .long _edata - _start // SizeOfCode .long 0 // SizeOfInitializedData .long 0 // SizeOfUninitializedData .long _start - ImageBase // AddressOfEntryPoint .long _start - ImageBase // BaseOfCode .long 0 // BaseOfData extra_header_fields: .long 0 // ImageBase .long 0x20 // SectionAlignment .long 0x8 // FileAlignment .short 0 // MajorOperatingSystemVersion .short 0 // MinorOperatingSystemVersion .short 0 // MajorImageVersion .short 0 // MinorImageVersion .short 0 // MajorSubsystemVersion .short 0 // MinorSubsystemVersion .long 0 // Win32VersionValue .long _edata - ImageBase // SizeOfImage // Everything before the kernel image is considered part of the header .long _start - ImageBase // SizeOfHeaders .long 0 // CheckSum .short EFI_SUBSYSTEM // Subsystem .short 0 // DllCharacteristics .long 0 // SizeOfStackReserve .long 0 // SizeOfStackCommit .long 0 // SizeOfHeapReserve .long 0 // SizeOfHeapCommit .long 0 // LoaderFlags .long 0x6 // NumberOfRvaAndSizes .quad 0 // ExportTable .quad 0 // ImportTable .quad 0 // ResourceTable .quad 0 // ExceptionTable .quad 0 // CertificationTable .quad 0 // BaseRelocationTable // Section table section_table: /* * The EFI application loader requires a relocation section * because EFI applications must be relocatable. This is a * dummy section as far as we are concerned. */ .ascii ".reloc" .byte 0 .byte 0 // end of 0 padding of section name .long 0 .long 0 .long 0 // SizeOfRawData .long 0 // PointerToRawData .long 0 // PointerToRelocations .long 0 // PointerToLineNumbers .short 0 // NumberOfRelocations .short 0 // NumberOfLineNumbers .long 0x42100040 // Characteristics (section flags) .ascii ".text" .byte 0 .byte 0 .byte 0 // end of 0 padding of section name .long _edata - _start // VirtualSize .long _start - ImageBase // VirtualAddress .long _edata - _start // SizeOfRawData .long _start - ImageBase // PointerToRawData .long 0 // PointerToRelocations (0 for executables) .long 0 // PointerToLineNumbers (0 for executables) .short 0 // NumberOfRelocations (0 for executables) .short 0 // NumberOfLineNumbers (0 for executables) .long 0xe0500020 // Characteristics (section flags) _start: stmfd sp!, {r0-r2, lr} mov r2, r0 mov r3, r1 adr r1, .L_DYNAMIC ldr r0, [r1] add r1, r0, r1 adr r0, ImageBase bl _relocate teq r0, #0 bne 0f ldmfd sp, {r0-r1} bl efi_main 0: add sp, sp, #12 ldr pc, [sp], #4 .L_DYNAMIC: .word _DYNAMIC - .
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
OUTPUT_FORMAT("elf64-ia64-little") OUTPUT_ARCH(ia64) ENTRY(_start_plabel) SECTIONS { . = 0; ImageBase = .; /* .hash and/or .gnu.hash MUST come first! */ .hash : { *(.hash) } .gnu.hash : { *(.gnu.hash) } . = ALIGN(4096); .text : { _text = .; *(.text) *(.text.*) *(.gnu.linkonce.t.*) . = ALIGN(16); } _etext = .; _text_size = . - _text; . = ALIGN(4096); __gp = ALIGN (8) + 0x200000; .sdata : { _data = .; *(.got.plt) *(.got) *(.srodata) *(.sdata) *(.sbss) *(.scommon) } . = ALIGN(4096); .data : { *(.rodata*) *(.ctors) *(.data*) *(.gnu.linkonce.d*) *(.plabel) /* data whose relocs we want to ignore */ /* the EFI loader doesn't seem to like a .bss section, so we stick it all into .data: */ *(.dynbss) *(.bss) *(COMMON) } .note.gnu.build-id : { *(.note.gnu.build-id) } . = ALIGN(4096); .dynamic : { *(.dynamic) } . = ALIGN(4096); .rela : { *(.rela.text) *(.rela.data*) *(.rela.sdata) *(.rela.got) *(.rela.gnu.linkonce.d*) *(.rela.stab) *(.rela.ctors) } _edata = .; _data_size = . - _etext; . = ALIGN(4096); .reloc : /* This is the PECOFF .reloc section! */ { *(.reloc) } . = ALIGN(4096); .dynsym : { *(.dynsym) } . = ALIGN(4096); .dynstr : { *(.dynstr) } /DISCARD/ : { *(.rela.plabel) *(.rela.reloc) *(.IA_64.unwind*) *(.IA64.unwind*) } }
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
/* reloc_ia64.S - position independent IA-64 ELF shared object relocator Copyright (C) 1999 Hewlett-Packard Co. Contributed by David Mosberger <[email protected]>. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Hewlett-Packard Co. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANYDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * This is written in assembly because the entire code needs to be position * independent. Note that the compiler does not generate code that's position * independent by itself because it relies on the global offset table being * relocated. */ .text .psr abi64 .psr lsb .lsb /* * This constant determines how many R_IA64_FPTR64LSB relocations we * can deal with. If you get EFI_BUFFER_TOO_SMALL errors, you may * need to increase this number. */ #define MAX_FUNCTION_DESCRIPTORS 750 #define ST_VALUE_OFF 8 /* offset of st_value in elf sym */ #define EFI_SUCCESS 0 #define EFI_LOAD_ERROR 1 #define EFI_BUFFER_TOO_SMALL 5 #define DT_NULL 0 /* Marks end of dynamic section */ #define DT_RELA 7 /* Address of Rela relocs */ #define DT_RELASZ 8 /* Total size of Rela relocs */ #define DT_RELAENT 9 /* Size of one Rela reloc */ #define DT_SYMTAB 6 /* Address of symbol table */ #define DT_SYMENT 11 /* Size of one symbol table entry */ #define R_IA64_NONE 0 #define R_IA64_REL64MSB 0x6e #define R_IA64_REL64LSB 0x6f #define R_IA64_DIR64MSB 0x26 #define R_IA64_DIR64LSB 0x27 #define R_IA64_FPTR64MSB 0x46 #define R_IA64_FPTR64LSB 0x47 #define ldbase in0 /* load address (address of .text) */ #define dyn in1 /* address of _DYNAMIC */ #define d_tag r16 #define d_val r17 #define rela r18 #define relasz r19 #define relaent r20 #define addr r21 #define r_info r22 #define r_offset r23 #define r_addend r24 #define r_type r25 #define r_sym r25 /* alias of r_type ! */ #define fptr r26 #define fptr_limit r27 #define symtab f8 #define syment f9 #define ftmp f10 #define target r16 #define val r17 #define NLOC 0 #define Pnull p6 #define Prela p7 #define Prelasz p8 #define Prelaent p9 #define Psymtab p10 #define Psyment p11 #define Pnone p6 #define Prel p7 #define Pfptr p8 #define Pmore p6 #define Poom p6 /* out-of-memory */ .global _relocate .proc _relocate _relocate: alloc r2=ar.pfs,2,0,0,0 movl fptr = @gprel(fptr_mem_base) ;; add fptr = fptr, gp movl fptr_limit = @gprel(fptr_mem_limit) ;; add fptr_limit = fptr_limit, gp search_dynamic: ld8 d_tag = [dyn],8 ;; ld8 d_val = [dyn],8 cmp.eq Pnull,p0 = DT_NULL,d_tag (Pnull) br.cond.sptk.few apply_relocs cmp.eq Prela,p0 = DT_RELA,d_tag cmp.eq Prelasz,p0 = DT_RELASZ,d_tag cmp.eq Psymtab,p0 = DT_SYMTAB,d_tag cmp.eq Psyment,p0 = DT_SYMENT,d_tag cmp.eq Prelaent,p0 = DT_RELAENT,d_tag ;; (Prela) add rela = d_val, ldbase (Prelasz) mov relasz = d_val (Prelaent) mov relaent = d_val (Psymtab) add val = d_val, ldbase ;; (Psyment) setf.sig syment = d_val ;; (Psymtab) setf.sig symtab = val br.sptk.few search_dynamic apply_loop: ld8 r_offset = [rela] add addr = 8,rela sub relasz = relasz,relaent ;; ld8 r_info = [addr],8 ;; ld8 r_addend = [addr] add target = ldbase, r_offset add rela = rela,relaent extr.u r_type = r_info, 0, 32 ;; cmp.eq Pnone,p0 = R_IA64_NONE,r_type cmp.eq Prel,p0 = R_IA64_REL64LSB,r_type cmp.eq Pfptr,p0 = R_IA64_FPTR64LSB,r_type (Prel) br.cond.sptk.few apply_REL64 ;; cmp.eq Prel,p0 = R_IA64_DIR64LSB,r_type // treat DIR64 just like REL64 (Pnone) br.cond.sptk.few apply_relocs (Prel) br.cond.sptk.few apply_REL64 (Pfptr) br.cond.sptk.few apply_FPTR64 mov r8 = EFI_LOAD_ERROR br.ret.sptk.few rp apply_relocs: cmp.ltu Pmore,p0=0,relasz (Pmore) br.cond.sptk.few apply_loop mov r8 = EFI_SUCCESS br.ret.sptk.few rp apply_REL64: ld8 val = [target] ;; add val = val,ldbase ;; st8 [target] = val br.cond.sptk.few apply_relocs // FPTR relocs are a bit more interesting: we need to lookup // the symbol's value in symtab, allocate 16 bytes of memory, // store the value in [target] in the first and the gp in the // second dword. apply_FPTR64: st8 [target] = fptr extr.u r_sym = r_info,32,32 add target = 8,fptr ;; setf.sig ftmp = r_sym mov r8=EFI_BUFFER_TOO_SMALL ;; cmp.geu Poom,p0 = fptr,fptr_limit xma.lu ftmp = ftmp,syment,symtab (Poom) br.ret.sptk.few rp ;; getf.sig addr = ftmp st8 [target] = gp ;; add addr = ST_VALUE_OFF, addr ;; ld8 val = [addr] ;; add val = val,ldbase ;; st8 [fptr] = val,16 br.cond.sptk.few apply_relocs .endp _relocate .data .align 16 fptr_mem_base: .space MAX_FUNCTION_DESCRIPTORS*16 fptr_mem_limit:
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
/* crt0-efi-ia32.S - x86 EFI startup code. Copyright (C) 1999 Hewlett-Packard Co. Contributed by David Mosberger <[email protected]>. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Hewlett-Packard Co. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANYDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ .text .align 4 .globl _start _start: pushl %ebp movl %esp,%ebp pushl 12(%ebp) # copy "image" argument pushl 8(%ebp) # copy "systab" argument call 0f 0: popl %eax movl %eax,%ebx addl $ImageBase-0b,%eax # %eax = ldbase addl $_DYNAMIC-0b,%ebx # %ebx = _DYNAMIC pushl %ebx # pass _DYNAMIC as second argument pushl %eax # pass ldbase as first argument call _relocate popl %ebx popl %ebx testl %eax,%eax jne .exit call efi_main # call app with "image" and "systab" argument .exit: leave ret // hand-craft a dummy .reloc section so EFI knows it's a relocatable executable: .data dummy: .long 0 #define IMAGE_REL_ABSOLUTE 0 .section .reloc .long dummy // Page RVA .long 10 // Block Size (2*4+2) .word (IMAGE_REL_ABSOLUTE<<12) + 0 // reloc for dummy
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
/* reloc_mips64el.c - position independent MIPS64 ELF shared object relocator Copyright (C) 2014 Linaro Ltd. <[email protected]> Copyright (C) 1999 Hewlett-Packard Co. Contributed by David Mosberger <[email protected]>. Copyright (C) 2017 Lemote Co. Contributed by Heiher <[email protected]> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Hewlett-Packard Co. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANYDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <efi.h> #include <efilib.h> #include <elf.h> EFI_STATUS _relocate (long ldbase, Elf64_Dyn *dyn, EFI_HANDLE image EFI_UNUSED, EFI_SYSTEM_TABLE *systab EFI_UNUSED) { long relsz = 0, relent = 0, gotsz = 0; Elf64_Rel *rel = 0; unsigned long *addr = 0; int i; for (i = 0; dyn[i].d_tag != DT_NULL; ++i) { switch (dyn[i].d_tag) { case DT_REL: rel = (Elf64_Rel*) ((unsigned long)dyn[i].d_un.d_ptr + ldbase); break; case DT_RELSZ: relsz = dyn[i].d_un.d_val; break; case DT_RELENT: relent = dyn[i].d_un.d_val; break; case DT_PLTGOT: addr = (unsigned long *) ((unsigned long)dyn[i].d_un.d_ptr + ldbase); break; case DT_MIPS_LOCAL_GOTNO: gotsz = dyn[i].d_un.d_val; break; default: break; } } if ((!rel && relent == 0) && (!addr && gotsz == 0)) return EFI_SUCCESS; if ((!rel && relent != 0) || (!addr && gotsz != 0)) return EFI_LOAD_ERROR; while (gotsz > 0) { *addr += ldbase; addr += 1; gotsz --; } while (relsz > 0) { /* apply the relocs */ switch (ELF64_R_TYPE (swap_uint64 (rel->r_info))) { case R_MIPS_NONE: break; case (R_MIPS_64 << 8) | R_MIPS_REL32: addr = (unsigned long *) (ldbase + rel->r_offset); *addr += ldbase; break; default: break; } rel = (Elf64_Rel*) ((char *) rel + relent); relsz -= relent; } return EFI_SUCCESS; }
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
/* crt0-efi-ia64.S - IA-64 EFI startup code. Copyright (C) 1999 Hewlett-Packard Co. Contributed by David Mosberger <[email protected]>. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Hewlett-Packard Co. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANYDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ .text .psr abi64 .psr lsb .lsb .proc _start _start: alloc loc0=ar.pfs,2,2,2,0 mov loc1=rp movl out0=@gprel(ImageBase) // out0 <- ImageBase (ldbase) ;; add out0=out0,gp movl out1=@gprel(_DYNAMIC) // out1 <- _DYNAMIC ;; // avoid WAW on CFM add out1=out1,gp br.call.sptk.few rp=_relocate .Lret0: cmp.ne p6,p0=r0,r8 // r8 == EFI_SUCCESS? (p6) br.cond.sptk.few .exit // no -> .Lret1: mov out0=in0 // image handle mov out1=in1 // systab br.call.sptk.few rp=efi_main .Lret2: .exit: mov ar.pfs=loc0 mov rp=loc1 ;; br.ret.sptk.few rp .endp _start // PE32+ wants a PLABEL, not the code address of the entry point: .align 16 .global _start_plabel .section .plabel, "a" _start_plabel: data8 _start data8 __gp // hand-craft a .reloc section for the plabel: #define IMAGE_REL_BASED_DIR64 10 .section .reloc, "a" data4 _start_plabel // Page RVA data4 12 // Block Size (2*4+2*2) data2 (IMAGE_REL_BASED_DIR64<<12) + 0 // reloc for plabel's entry point data2 (IMAGE_REL_BASED_DIR64<<12) + 8 // reloc for plabel's global pointer
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
/* crt0-efi-x86_64.S - x86_64 EFI startup code. Copyright (C) 1999 Hewlett-Packard Co. Contributed by David Mosberger <[email protected]>. Copyright (C) 2005 Intel Co. Contributed by Fenghua Yu <[email protected]>. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Hewlett-Packard Co. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANYDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ .text .align 4 .globl _start _start: subq $8, %rsp pushq %rcx pushq %rdx 0: lea ImageBase(%rip), %rdi lea _DYNAMIC(%rip), %rsi popq %rcx popq %rdx pushq %rcx pushq %rdx call _relocate popq %rdi popq %rsi call efi_main addq $8, %rsp .exit: ret // hand-craft a dummy .reloc section so EFI knows it's a relocatable executable: .data dummy: .long 0 #define IMAGE_REL_ABSOLUTE 0 .section .reloc, "a" label1: .long dummy-label1 // Page RVA .long 10 // Block Size (2*4+2) .word (IMAGE_REL_ABSOLUTE<<12) + 0 // reloc for dummy
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
OUTPUT_FORMAT("elf64-tradlittlemips", "elf64-tradbigmips", "elf64-tradlittlemips") OUTPUT_ARCH(mips) ENTRY(_start) SECTIONS { .text 0x0 : { _text = .; *(.text.head) *(.text) *(.text.*) *(.gnu.linkonce.t.*) *(.srodata) *(.rodata*) . = ALIGN(16); } _etext = .; _text_size = . - _text; .dynamic : { *(.dynamic) } .data : { _data = .; *(.sdata) *(.data) *(.data1) *(.data.*) *(.got.plt) HIDDEN (_gp = ALIGN (16) + 0x7ff0); *(.got) /* the EFI loader doesn't seem to like a .bss section, so we stick it all into .data: */ . = ALIGN(16); _bss = .; *(.sbss) *(.scommon) *(.dynbss) *(.bss) *(COMMON) . = ALIGN(16); _bss_end = .; } .rel.dyn : { *(.rel.dyn) } .rel.plt : { *(.rel.plt) } .rel.got : { *(.rel.got) } .rel.data : { *(.rel.data) *(.rel.data*) } _edata = .; _data_size = . - _etext; . = ALIGN(4096); .dynsym : { *(.dynsym) } . = ALIGN(4096); .dynstr : { *(.dynstr) } . = ALIGN(4096); .note.gnu.build-id : { *(.note.gnu.build-id) } /DISCARD/ : { *(.rel.reloc) *(.eh_frame) *(.MIPS.abiflags) *(.note.GNU-stack) } .comment 0 : { *(.comment) } }
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
# # Copyright (C) 1999-2001 Hewlett-Packard Co. # Contributed by David Mosberger <[email protected]> # Contributed by Stephane Eranian <[email protected]> # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials # provided with the distribution. # * Neither the name of Hewlett-Packard Co. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND # CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, # INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS # BE LIABLE FOR ANYDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, # OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF # THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # SRCDIR = . VPATH = $(SRCDIR) include $(SRCDIR)/../Make.defaults TOPDIR = $(SRCDIR)/.. CDIR=$(TOPDIR)/.. FILES = reloc_$(ARCH) OBJS = $(FILES:%=%.o) # on aarch64, avoid jump tables before all relocations have been processed reloc_aarch64.o: CFLAGS += -fno-jump-tables TARGETS = crt0-efi-$(ARCH).o libgnuefi.a all: $(TARGETS) libgnuefi.a: $(OBJS) $(AR) $(ARFLAGS) $@ $^ clean: rm -f $(TARGETS) *~ *.o $(OBJS) install: mkdir -p $(INSTALLROOT)$(LIBDIR) $(INSTALL) -m 644 $(TARGETS) $(INSTALLROOT)$(LIBDIR) ifneq (,$(findstring FreeBSD,$(OS))) ifeq ($(ARCH),x86_64) $(INSTALL) -m 644 $(SRCDIR)/elf_$(ARCH)_fbsd_efi.lds $(INSTALLROOT)$(LIBDIR) else $(INSTALL) -m 644 $(SRCDIR)/elf_$(ARCH)_efi.lds $(INSTALLROOT)$(LIBDIR) endif else $(INSTALL) -m 644 $(SRCDIR)/elf_$(ARCH)_efi.lds $(INSTALLROOT)$(LIBDIR) endif include $(SRCDIR)/../Make.rules
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
/* * crt0-efi-aarch64.S - PE/COFF header for AArch64 EFI applications * * Copright (C) 2014 Linaro Ltd. <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice and this list of conditions, without modification. * 2. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * Alternatively, this software may be distributed under the terms of the * GNU General Public License as published by the Free Software Foundation; * either version 2 of the License, or (at your option) any later version. */ .section .text.head /* * Magic "MZ" signature for PE/COFF */ .globl ImageBase ImageBase: .ascii "MZ" .skip 58 // 'MZ' + pad + offset == 64 .long pe_header - ImageBase // Offset to the PE header. pe_header: .ascii "PE" .short 0 coff_header: .short 0xaa64 // AArch64 .short 2 // nr_sections .long 0 // TimeDateStamp .long 0 // PointerToSymbolTable .long 1 // NumberOfSymbols .short section_table - optional_header // SizeOfOptionalHeader .short 0x206 // Characteristics. // IMAGE_FILE_DEBUG_STRIPPED | // IMAGE_FILE_EXECUTABLE_IMAGE | // IMAGE_FILE_LINE_NUMS_STRIPPED optional_header: .short 0x20b // PE32+ format .byte 0x02 // MajorLinkerVersion .byte 0x14 // MinorLinkerVersion .long _data - _start // SizeOfCode .long _data_size // SizeOfInitializedData .long 0 // SizeOfUninitializedData .long _start - ImageBase // AddressOfEntryPoint .long _start - ImageBase // BaseOfCode extra_header_fields: .quad 0 // ImageBase .long 0x1000 // SectionAlignment .long 0x200 // FileAlignment .short 0 // MajorOperatingSystemVersion .short 0 // MinorOperatingSystemVersion .short 0 // MajorImageVersion .short 0 // MinorImageVersion .short 0 // MajorSubsystemVersion .short 0 // MinorSubsystemVersion .long 0 // Win32VersionValue .long _edata - ImageBase // SizeOfImage // Everything before the kernel image is considered part of the header .long _start - ImageBase // SizeOfHeaders .long 0 // CheckSum .short EFI_SUBSYSTEM // Subsystem .short 0 // DllCharacteristics .quad 0 // SizeOfStackReserve .quad 0 // SizeOfStackCommit .quad 0 // SizeOfHeapReserve .quad 0 // SizeOfHeapCommit .long 0 // LoaderFlags .long 0x6 // NumberOfRvaAndSizes .quad 0 // ExportTable .quad 0 // ImportTable .quad 0 // ResourceTable .quad 0 // ExceptionTable .quad 0 // CertificationTable .quad 0 // BaseRelocationTable // Section table section_table: .ascii ".text\0\0\0" .long _data - _start // VirtualSize .long _start - ImageBase // VirtualAddress .long _data - _start // SizeOfRawData .long _start - ImageBase // PointerToRawData .long 0 // PointerToRelocations (0 for executables) .long 0 // PointerToLineNumbers (0 for executables) .short 0 // NumberOfRelocations (0 for executables) .short 0 // NumberOfLineNumbers (0 for executables) .long 0x60000020 // Characteristics (section flags) .ascii ".data\0\0\0" .long _data_size // VirtualSize .long _data - ImageBase // VirtualAddress .long _data_size // SizeOfRawData .long _data - ImageBase // PointerToRawData .long 0 // PointerToRelocations (0 for executables) .long 0 // PointerToLineNumbers (0 for executables) .short 0 // NumberOfRelocations (0 for executables) .short 0 // NumberOfLineNumbers (0 for executables) .long 0xc0000040 // Characteristics (section flags) .align 12 _start: stp x29, x30, [sp, #-32]! mov x29, sp stp x0, x1, [sp, #16] mov x2, x0 mov x3, x1 adr x0, ImageBase adrp x1, _DYNAMIC add x1, x1, #:lo12:_DYNAMIC bl _relocate cbnz x0, 0f ldp x0, x1, [sp, #16] bl efi_main 0: ldp x29, x30, [sp], #32 ret
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
/* Same as elf_x86_64_efi.lds, except for OUTPUT_FORMAT below - KEEP IN SYNC */ OUTPUT_FORMAT("elf64-x86-64-freebsd", "elf64-x86-64-freebsd", "elf64-x86-64-freebsd") OUTPUT_ARCH(i386:x86-64) ENTRY(_start) SECTIONS { . = 0; ImageBase = .; /* .hash and/or .gnu.hash MUST come first! */ .hash : { *(.hash) } .gnu.hash : { *(.gnu.hash) } . = ALIGN(4096); .eh_frame : { *(.eh_frame) } . = ALIGN(4096); .text : { _text = .; *(.text) . = ALIGN(16); } _etext = .; _text_size = . - _text; .reloc : { *(.reloc) } . = ALIGN(4096); .data : { _data = .; *(.rodata*) *(.got.plt) *(.got) *(.data*) *(.sdata) /* the EFI loader doesn't seem to like a .bss section, so we stick it all into .data: */ *(.sbss) *(.scommon) *(.dynbss) *(.bss) *(COMMON) *(.rel.local) } .note.gnu.build-id : { *(.note.gnu.build-id) } . = ALIGN(4096); .dynamic : { *(.dynamic) } . = ALIGN(4096); .rela : { *(.rela.data*) *(.rela.got) *(.rela.stab) } _edata = .; _data_size = . - _etext; . = ALIGN(4096); .dynsym : { *(.dynsym) } . = ALIGN(4096); .dynstr : { *(.dynstr) } . = ALIGN(4096); .ignored.reloc : { *(.rela.reloc) } }
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
OUTPUT_FORMAT("elf32-i386-freebsd", "elf32-i386-freebsd", "elf32-i386-freebsd") OUTPUT_ARCH(i386) ENTRY(_start) SECTIONS { . = 0; ImageBase = .; /* .hash and/or .gnu.hash MUST come first! */ .hash : { *(.hash) } .gnu.hash : { *(.gnu.hash) } . = ALIGN(4096); .text : { _text = .; *(.text) *(.text.*) *(.gnu.linkonce.t.*) . = ALIGN(16); } _etext = .; _text_size = . - _text; . = ALIGN(4096); .sdata : { _data = .; *(.got.plt) *(.got) *(.srodata) *(.sdata) *(.sbss) *(.scommon) } . = ALIGN(4096); .data : { *(.rodata*) *(.data) *(.data1) *(.data.*) *(.sdata) *(.got.plt) *(.got) /* the EFI loader doesn't seem to like a .bss section, so we stick it all into .data: */ *(.sbss) *(.scommon) *(.dynbss) *(.bss) *(COMMON) } .note.gnu.build-id : { *(.note.gnu.build-id) } . = ALIGN(4096); .dynamic : { *(.dynamic) } . = ALIGN(4096); .rel : { *(.rel.data) *(.rel.data.*) *(.rel.got) *(.rel.stab) *(.data.rel.ro.local) *(.data.rel.local) *(.data.rel.ro) *(.data.rel*) } _edata = .; _data_size = . - _etext; . = ALIGN(4096); .reloc : /* This is the PECOFF .reloc section! */ { *(.reloc) } . = ALIGN(4096); .dynsym : { *(.dynsym) } . = ALIGN(4096); .dynstr : { *(.dynstr) } . = ALIGN(4096); /DISCARD/ : { *(.rel.reloc) *(.eh_frame) *(.note.GNU-stack) } .comment 0 : { *(.comment) } }
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
OUTPUT_FORMAT("elf32-littlearm", "elf32-littlearm", "elf32-littlearm") OUTPUT_ARCH(arm) ENTRY(_start) SECTIONS { .text 0x0 : { _text = .; *(.text.head) *(.text) *(.text.*) *(.gnu.linkonce.t.*) *(.srodata) *(.rodata*) . = ALIGN(16); } _etext = .; _text_size = . - _text; .dynamic : { *(.dynamic) } .data : { _data = .; *(.sdata) *(.data) *(.data1) *(.data.*) *(.got.plt) *(.got) /* the EFI loader doesn't seem to like a .bss section, so we stick it all into .data: */ . = ALIGN(16); _bss = .; *(.sbss) *(.scommon) *(.dynbss) *(.bss) *(.bss.*) *(COMMON) . = ALIGN(16); _bss_end = .; } .rel.dyn : { *(.rel.dyn) } .rel.plt : { *(.rel.plt) } .rel.got : { *(.rel.got) } .rel.data : { *(.rel.data) *(.rel.data*) } _edata = .; _data_size = . - _etext; . = ALIGN(4096); .dynsym : { *(.dynsym) } . = ALIGN(4096); .dynstr : { *(.dynstr) } . = ALIGN(4096); .note.gnu.build-id : { *(.note.gnu.build-id) } /DISCARD/ : { *(.rel.reloc) *(.eh_frame) *(.note.GNU-stack) } .comment 0 : { *(.comment) } }
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
/* * crt0-efi-mips64el.S - PE/COFF header for MIPS64 EFI applications * * Copright (C) 2014 Linaro Ltd. <[email protected]> * Copright (C) 2017 Heiher <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice and this list of conditions, without modification. * 2. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * Alternatively, this software may be distributed under the terms of the * GNU General Public License as published by the Free Software Foundation; * either version 2 of the License, or (at your option) any later version. */ .section .text.head /* * Magic "MZ" signature for PE/COFF */ .globl ImageBase ImageBase: .ascii "MZ" .skip 58 // 'MZ' + pad + offset == 64 .long pe_header - ImageBase // Offset to the PE header. pe_header: .ascii "PE" .short 0 coff_header: .short 0x166 // MIPS little endian .short 2 // nr_sections .long 0 // TimeDateStamp .long 0 // PointerToSymbolTable .long 1 // NumberOfSymbols .short section_table - optional_header // SizeOfOptionalHeader .short 0x206 // Characteristics. // IMAGE_FILE_DEBUG_STRIPPED | // IMAGE_FILE_EXECUTABLE_IMAGE | // IMAGE_FILE_LINE_NUMS_STRIPPED optional_header: .short 0x20b // PE32+ format .byte 0x02 // MajorLinkerVersion .byte 0x14 // MinorLinkerVersion .long _edata - _start // SizeOfCode .long 0 // SizeOfInitializedData .long 0 // SizeOfUninitializedData .long _start - ImageBase // AddressOfEntryPoint .long _start - ImageBase // BaseOfCode extra_header_fields: .quad 0 // ImageBase .long 0x20 // SectionAlignment .long 0x8 // FileAlignment .short 0 // MajorOperatingSystemVersion .short 0 // MinorOperatingSystemVersion .short 0 // MajorImageVersion .short 0 // MinorImageVersion .short 0 // MajorSubsystemVersion .short 0 // MinorSubsystemVersion .long 0 // Win32VersionValue .long _edata - ImageBase // SizeOfImage // Everything before the kernel image is considered part of the header .long _start - ImageBase // SizeOfHeaders .long 0 // CheckSum .short EFI_SUBSYSTEM // Subsystem .short 0 // DllCharacteristics .quad 0 // SizeOfStackReserve .quad 0 // SizeOfStackCommit .quad 0 // SizeOfHeapReserve .quad 0 // SizeOfHeapCommit .long 0 // LoaderFlags .long 0x6 // NumberOfRvaAndSizes .quad 0 // ExportTable .quad 0 // ImportTable .quad 0 // ResourceTable .quad 0 // ExceptionTable .quad 0 // CertificationTable .quad 0 // BaseRelocationTable // Section table section_table: /* * The EFI application loader requires a relocation section * because EFI applications must be relocatable. This is a * dummy section as far as we are concerned. */ .ascii ".reloc" .byte 0 .byte 0 // end of 0 padding of section name .long 0 .long 0 .long 0 // SizeOfRawData .long 0 // PointerToRawData .long 0 // PointerToRelocations .long 0 // PointerToLineNumbers .short 0 // NumberOfRelocations .short 0 // NumberOfLineNumbers .long 0x42100040 // Characteristics (section flags) .ascii ".text" .byte 0 .byte 0 .byte 0 // end of 0 padding of section name .long _edata - _start // VirtualSize .long _start - ImageBase // VirtualAddress .long _edata - _start // SizeOfRawData .long _start - ImageBase // PointerToRawData .long 0 // PointerToRelocations (0 for executables) .long 0 // PointerToLineNumbers (0 for executables) .short 0 // NumberOfRelocations (0 for executables) .short 0 // NumberOfLineNumbers (0 for executables) .long 0xe0500020 // Characteristics (section flags) .set push .set noreorder .align 4 .globl _start .ent _start .type _start, @function _start: daddiu $sp, -32 sd $ra, ($sp) // Get pc & gp .align 3 bal 1f sd $gp, 8($sp) _pc: .dword _gp .dword _DYNAMIC .dword _relocate 1: // pc in ra ld $gp, ($ra) dli $t0, _pc dsubu $gp, $t0 daddu $gp, $ra sd $a0, 16($sp) sd $a1, 24($sp) // a2: ImageHandle move $a2, $a0 // a3: SystemTable move $a3, $a1 // a0: ImageBase dli $t1, ImageBase - _pc daddu $a0, $ra, $t1 // a1: DynamicSection ld $t1, 8($ra) dsubu $t1, $t0 daddu $a1, $ra, $t1 // call _relocate ld $t1, 16($ra) dsubu $t1, $t0 daddu $t9, $ra, $t1 jalr $t9 nop bnez $v0, 1b nop // a0: ImageHandle ld $a0, 16($sp) // call efi_main dla $t9, efi_main jalr $t9 // a1: SystemTable ld $a1, 24($sp) 1: ld $gp, 8($sp) ld $ra, ($sp) jr $ra daddiu $sp, 32 .end _start .set pop
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
/* reloc_aarch64.c - position independent x86 ELF shared object relocator Copyright (C) 2014 Linaro Ltd. <[email protected]> Copyright (C) 1999 Hewlett-Packard Co. Contributed by David Mosberger <[email protected]>. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Hewlett-Packard Co. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANYDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <efi.h> #include <efilib.h> #include <elf.h> EFI_STATUS _relocate (long ldbase, Elf64_Dyn *dyn, EFI_HANDLE image EFI_UNUSED, EFI_SYSTEM_TABLE *systab EFI_UNUSED) { long relsz = 0, relent = 0; Elf64_Rela *rel = 0; unsigned long *addr; int i; for (i = 0; dyn[i].d_tag != DT_NULL; ++i) { switch (dyn[i].d_tag) { case DT_RELA: rel = (Elf64_Rela*) ((unsigned long)dyn[i].d_un.d_ptr + ldbase); break; case DT_RELASZ: relsz = dyn[i].d_un.d_val; break; case DT_RELAENT: relent = dyn[i].d_un.d_val; break; default: break; } } if (!rel && relent == 0) return EFI_SUCCESS; if (!rel || relent == 0) return EFI_LOAD_ERROR; while (relsz > 0) { /* apply the relocs */ switch (ELF64_R_TYPE (rel->r_info)) { case R_AARCH64_NONE: break; case R_AARCH64_RELATIVE: addr = (unsigned long *) (ldbase + rel->r_offset); *addr = ldbase + rel->r_addend; break; default: break; } rel = (Elf64_Rela*) ((char *) rel + relent); relsz -= relent; } return EFI_SUCCESS; }
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
# # Copyright (C) 1999-2001 Hewlett-Packard Co. # Contributed by David Mosberger <[email protected]> # Contributed by Stephane Eranian <[email protected]> # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials # provided with the distribution. # * Neither the name of Hewlett-Packard Co. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND # CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, # INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS # BE LIABLE FOR ANYDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, # OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF # THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # SRCDIR = . VPATH = $(SRCDIR) include $(SRCDIR)/../Make.defaults TOPDIR = $(SRCDIR)/.. CDIR=$(TOPDIR)/.. LINUX_HEADERS = /usr/src/sys/build CPPFLAGS += -D__KERNEL__ -I$(LINUX_HEADERS)/include CRTOBJS = ../gnuefi/crt0-efi-$(ARCH).o LDSCRIPT = $(TOPDIR)/gnuefi/elf_$(ARCH)_efi.lds ifneq (,$(findstring FreeBSD,$(OS))) LDSCRIPT = $(TOPDIR)/gnuefi/elf_$(ARCH)_fbsd_efi.lds endif LDFLAGS += -shared -Bsymbolic -L../lib -L../gnuefi $(CRTOBJS) LOADLIBES += -lefi -lgnuefi LOADLIBES += $(LIBGCC) LOADLIBES += -T $(LDSCRIPT) TARGET_APPS = main.efi TARGET_BSDRIVERS = TARGET_RTDRIVERS = ifneq ($(HAVE_EFI_OBJCOPY),) FORMAT := --target efi-app-$(ARCH) $(TARGET_BSDRIVERS): FORMAT=--target efi-bsdrv-$(ARCH) $(TARGET_RTDRIVERS): FORMAT=--target efi-rtdrv-$(ARCH) else SUBSYSTEM := 0xa $(TARGET_BSDRIVERS): SUBSYSTEM = 0xb $(TARGET_RTDRIVERS): SUBSYSTEM = 0xc FORMAT := -O binary LDFLAGS += --defsym=EFI_SUBSYSTEM=$(SUBSYSTEM) endif TARGETS = $(TARGET_APPS) $(TARGET_BSDRIVERS) $(TARGET_RTDRIVERS) CFLAGS += -Wno-error=unused-parameter -Wno-error=unused-variable all: $(TARGETS) clean: rm -f $(TARGETS) *~ *.o *.so .PHONY: install include $(SRCDIR)/../Make.rules
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
#include <efi.h> #include <efilib.h> #include <elf.h> typedef unsigned long long size_t; EFI_FILE* LoadFile(EFI_FILE* Directory, CHAR16* Path, EFI_HANDLE ImageHandle, EFI_SYSTEM_TABLE* SystemTable){ EFI_FILE* LoadedFile; EFI_LOADED_IMAGE_PROTOCOL* LoadedImage; SystemTable->BootServices->HandleProtocol(ImageHandle, &gEfiLoadedImageProtocolGuid, (void**)&LoadedImage); EFI_SIMPLE_FILE_SYSTEM_PROTOCOL* FileSystem; SystemTable->BootServices->HandleProtocol(LoadedImage->DeviceHandle, &gEfiSimpleFileSystemProtocolGuid, (void**)&FileSystem); if (Directory == NULL){ FileSystem->OpenVolume(FileSystem, &Directory); } EFI_STATUS s = Directory->Open(Directory, &LoadedFile, Path, EFI_FILE_MODE_READ, EFI_FILE_READ_ONLY); if (s != EFI_SUCCESS){ return NULL; } return LoadedFile; } int memcmp(const void* aptr, const void* bptr, size_t n){ const unsigned char* a = aptr, *b = bptr; for (size_t i = 0; i < n; i++){ if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; } return 0; } EFI_STATUS efi_main (EFI_HANDLE ImageHandle, EFI_SYSTEM_TABLE *SystemTable) { InitializeLib(ImageHandle, SystemTable); Print(L"String blah blah blah \n\r"); EFI_FILE* Kernel = LoadFile(NULL, L"kernel.elf", ImageHandle, SystemTable); if (Kernel == NULL){ Print(L"Could not load kernel \n\r"); } else{ Print(L"Kernel Loaded Successfully \n\r"); } Elf64_Ehdr header; { UINTN FileInfoSize; EFI_FILE_INFO* FileInfo; Kernel->GetInfo(Kernel, &gEfiFileInfoGuid, &FileInfoSize, NULL); SystemTable->BootServices->AllocatePool(EfiLoaderData, FileInfoSize, (void**)&FileInfo); Kernel->GetInfo(Kernel, &gEfiFileInfoGuid, &FileInfoSize, (void**)&FileInfo); UINTN size = sizeof(header); Kernel->Read(Kernel, &size, &header); } if ( memcmp(&header.e_ident[EI_MAG0], ELFMAG, SELFMAG) != 0 || header.e_ident[EI_CLASS] != ELFCLASS64 || header.e_ident[EI_DATA] != ELFDATA2LSB || header.e_type != ET_EXEC || header.e_machine != EM_X86_64 || header.e_version != EV_CURRENT ) { Print(L"kernel format is bad\r\n"); } else { Print(L"kernel header successfully verified\r\n"); } Elf64_Phdr* phdrs; { Kernel->SetPosition(Kernel, header.e_phoff); UINTN size = header.e_phnum * header.e_phentsize; SystemTable->BootServices->AllocatePool(EfiLoaderData, size, (void**)&phdrs); Kernel->Read(Kernel, &size, phdrs); } for ( Elf64_Phdr* phdr = phdrs; (char*)phdr < (char*)phdrs + header.e_phnum * header.e_phentsize; phdr = (Elf64_Phdr*)((char*)phdr + header.e_phentsize) ) { switch (phdr->p_type){ case PT_LOAD: { int pages = (phdr->p_memsz + 0x1000 - 1) / 0x1000; Elf64_Addr segment = phdr->p_paddr; SystemTable->BootServices->AllocatePages(AllocateAddress, EfiLoaderData, pages, &segment); Kernel->SetPosition(Kernel, phdr->p_offset); UINTN size = phdr->p_filesz; Kernel->Read(Kernel, &size, (void*)segment); break; } } } Print(L"Kernel Loaded\n\r"); int (*KernelStart)() = ((__attribute__((sysv_abi)) int (*)() ) header.e_entry); Print(L"%d\r\n", KernelStart()); return EFI_SUCCESS; // Exit the UEFI application }
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
/*++ Copyright (c) 1998 Intel Corporation Module Name: BoxDraw.c Abstract: Lib functions to support Box Draw Unicode code pages. Revision History --*/ #include "lib.h" typedef struct { CHAR16 Unicode; CHAR8 PcAnsi; CHAR8 Ascii; } UNICODE_TO_CHAR; // // This list is used to define the valid extend chars. // It also provides a mapping from Unicode to PCANSI or // ASCII. The ASCII mapping we just made up. // // STATIC UNICODE_TO_CHAR UnicodeToPcAnsiOrAscii[] = { { BOXDRAW_HORIZONTAL, 0xc4, L'-'}, { BOXDRAW_VERTICAL, 0xb3, L'|'}, { BOXDRAW_DOWN_RIGHT, 0xda, L'/'}, { BOXDRAW_DOWN_LEFT, 0xbf, L'\\'}, { BOXDRAW_UP_RIGHT, 0xc0, L'\\'}, { BOXDRAW_UP_LEFT, 0xd9, L'/'}, { BOXDRAW_VERTICAL_RIGHT, 0xc3, L'|'}, { BOXDRAW_VERTICAL_LEFT, 0xb4, L'|'}, { BOXDRAW_DOWN_HORIZONTAL, 0xc2, L'+'}, { BOXDRAW_UP_HORIZONTAL, 0xc1, L'+'}, { BOXDRAW_VERTICAL_HORIZONTAL, 0xc5, L'+'}, { BOXDRAW_DOUBLE_HORIZONTAL, 0xcd, L'-'}, { BOXDRAW_DOUBLE_VERTICAL, 0xba, L'|'}, { BOXDRAW_DOWN_RIGHT_DOUBLE, 0xd5, L'/'}, { BOXDRAW_DOWN_DOUBLE_RIGHT, 0xd6, L'/'}, { BOXDRAW_DOUBLE_DOWN_RIGHT, 0xc9, L'/'}, { BOXDRAW_DOWN_LEFT_DOUBLE, 0xb8, L'\\'}, { BOXDRAW_DOWN_DOUBLE_LEFT, 0xb7, L'\\'}, { BOXDRAW_DOUBLE_DOWN_LEFT, 0xbb, L'\\'}, { BOXDRAW_UP_RIGHT_DOUBLE, 0xd4, L'\\'}, { BOXDRAW_UP_DOUBLE_RIGHT, 0xd3, L'\\'}, { BOXDRAW_DOUBLE_UP_RIGHT, 0xc8, L'\\'}, { BOXDRAW_UP_LEFT_DOUBLE, 0xbe, L'/'}, { BOXDRAW_UP_DOUBLE_LEFT, 0xbd, L'/'}, { BOXDRAW_DOUBLE_UP_LEFT, 0xbc, L'/'}, { BOXDRAW_VERTICAL_RIGHT_DOUBLE, 0xc6, L'|'}, { BOXDRAW_VERTICAL_DOUBLE_RIGHT, 0xc7, L'|'}, { BOXDRAW_DOUBLE_VERTICAL_RIGHT, 0xcc, L'|'}, { BOXDRAW_VERTICAL_LEFT_DOUBLE, 0xb5, L'|'}, { BOXDRAW_VERTICAL_DOUBLE_LEFT, 0xb6, L'|'}, { BOXDRAW_DOUBLE_VERTICAL_LEFT, 0xb9, L'|'}, { BOXDRAW_DOWN_HORIZONTAL_DOUBLE, 0xd1, L'+'}, { BOXDRAW_DOWN_DOUBLE_HORIZONTAL, 0xd2, L'+'}, { BOXDRAW_DOUBLE_DOWN_HORIZONTAL, 0xcb, L'+'}, { BOXDRAW_UP_HORIZONTAL_DOUBLE, 0xcf, L'+'}, { BOXDRAW_UP_DOUBLE_HORIZONTAL, 0xd0, L'+'}, { BOXDRAW_DOUBLE_UP_HORIZONTAL, 0xca, L'+'}, { BOXDRAW_VERTICAL_HORIZONTAL_DOUBLE, 0xd8, L'+'}, { BOXDRAW_VERTICAL_DOUBLE_HORIZONTAL, 0xd7, L'+'}, { BOXDRAW_DOUBLE_VERTICAL_HORIZONTAL, 0xce, L'+'}, { BLOCKELEMENT_FULL_BLOCK, 0xdb, L'*'}, { BLOCKELEMENT_LIGHT_SHADE, 0xb0, L'+'}, { GEOMETRICSHAPE_UP_TRIANGLE, 0x1e, L'^'}, { GEOMETRICSHAPE_RIGHT_TRIANGLE, 0x10, L'>'}, { GEOMETRICSHAPE_DOWN_TRIANGLE, 0x1f, L'v'}, { GEOMETRICSHAPE_LEFT_TRIANGLE, 0x11, L'<'}, /* BugBug: Left Arrow is an ESC. We can not make it print on a PCANSI terminal. If we can make left arrow come out on PC ANSI we can add it back. { ARROW_LEFT, 0x1b, L'<'}, */ { ARROW_UP, 0x18, L'^'}, /* BugBut: Took out left arrow so right has to go too. { ARROW_RIGHT, 0x1a, L'>'}, */ { ARROW_DOWN, 0x19, L'v'}, { 0x0000, 0x00, L'\0' } }; BOOLEAN LibIsValidTextGraphics ( IN CHAR16 Graphic, OUT CHAR8 *PcAnsi, OPTIONAL OUT CHAR8 *Ascii OPTIONAL ) /*++ Routine Description: Detects if a Unicode char is for Box Drawing text graphics. Arguments: Grphic - Unicode char to test. PcAnsi - Optional pointer to return PCANSI equivalent of Graphic. Asci - Optional pointer to return Ascii equivalent of Graphic. Returns: TRUE if Gpaphic is a supported Unicode Box Drawing character. --*/{ UNICODE_TO_CHAR *Table; if ((((Graphic & 0xff00) != 0x2500) && ((Graphic & 0xff00) != 0x2100))) { // // Unicode drawing code charts are all in the 0x25xx range, // arrows are 0x21xx // return FALSE; } for (Table = UnicodeToPcAnsiOrAscii; Table->Unicode != 0x0000; Table++) { if (Graphic == Table->Unicode) { if (PcAnsi) { *PcAnsi = Table->PcAnsi; } if (Ascii) { *Ascii = Table->Ascii; } return TRUE; } } return FALSE; } BOOLEAN IsValidAscii ( IN CHAR16 Ascii ) { if ((Ascii >= 0x20) && (Ascii <= 0x7f)) { return TRUE; } return FALSE; } BOOLEAN IsValidEfiCntlChar ( IN CHAR16 c ) { if (c == CHAR_NULL || c == CHAR_BACKSPACE || c == CHAR_LINEFEED || c == CHAR_CARRIAGE_RETURN) { return TRUE; } return FALSE; }
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
/*++ Copyright (c) 1998 Intel Corporation Module Name: lock.c Abstract: Implements FLOCK Revision History --*/ #include "lib.h" VOID InitializeLock ( IN OUT FLOCK *Lock, IN EFI_TPL Priority ) /*++ Routine Description: Initialize a basic mutual exclusion lock. Each lock provides mutual exclusion access at it's task priority level. Since there is no-premption (at any TPL) or multiprocessor support, acquiring the lock only consists of raising to the locks TPL. Note on a debug build the lock is acquired and released to help ensure proper usage. Arguments: Lock - The FLOCK structure to initialize Priority - The task priority level of the lock Returns: An initialized F Lock structure. --*/ { Lock->Tpl = Priority; Lock->OwnerTpl = 0; Lock->Lock = 0; } VOID AcquireLock ( IN FLOCK *Lock ) /*++ Routine Description: Raising to the task priority level of the mutual exclusion lock, and then acquires ownership of the lock. Arguments: Lock - The lock to acquire Returns: Lock owned --*/ { RtAcquireLock (Lock); } VOID ReleaseLock ( IN FLOCK *Lock ) /*++ Routine Description: Releases ownership of the mutual exclusion lock, and restores the previous task priority level. Arguments: Lock - The lock to release Returns: Lock unowned --*/ { RtReleaseLock (Lock); }
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
#include "lib.h" #include "efiprot.h" #include "efishellintf.h" #include "efishellparm.h" #ifndef MAX_ARGV_CONTENTS_SIZE # define MAX_CMDLINE_SIZE 1024 #endif #ifndef MAX_ARGC # define MAX_CMDLINE_ARGC 32 #endif /* Parse LoadedImage options area, called only in case the regular shell protos are not available. Format of LoadedImage->LoadOptions appears to be a single-space-separated list of args (looks like the shell already pre-parses the input, it apparently folds several consecutive spaces into one): argv[0] space argv[1] (etc.) argv[N] space \0 cwd \0 other data For safety, we support the trailing \0 without a space before, as well as several consecutive spaces (-> several args). */ static INTN GetShellArgcArgvFromLoadedImage( EFI_HANDLE ImageHandle, CHAR16 **ResultArgv[] ) { EFI_STATUS Status; void *LoadedImage = NULL; static CHAR16 ArgvContents[MAX_CMDLINE_SIZE]; static CHAR16 *Argv[MAX_CMDLINE_ARGC], *ArgStart, *c; UINTN Argc = 0, BufLen; Status = uefi_call_wrapper(BS->OpenProtocol, 6, ImageHandle, &LoadedImageProtocol, &LoadedImage, ImageHandle, NULL, EFI_OPEN_PROTOCOL_GET_PROTOCOL ); if (EFI_ERROR(Status)) return -1; BufLen = ((EFI_LOADED_IMAGE *)LoadedImage)->LoadOptionsSize; if (BufLen < 2) /* We are expecting at least a \0 */ return -1; else if (BufLen > sizeof(ArgvContents)) BufLen = sizeof(ArgvContents); CopyMem(ArgvContents, ((EFI_LOADED_IMAGE *)LoadedImage)->LoadOptions, BufLen); ArgvContents[MAX_CMDLINE_SIZE - 1] = L'\0'; for (c = ArgStart = ArgvContents ; *c != L'\0' ; ++c) { if (*c == L' ') { *c = L'\0'; if (Argc < MAX_CMDLINE_ARGC) Argv[Argc++] = ArgStart; ArgStart = c + 1; } } if ((*ArgStart != L'\0') && (Argc < MAX_CMDLINE_ARGC)) Argv[Argc++] = ArgStart; // Print(L"Got argc/argv from loaded image proto\n"); *ResultArgv = Argv; return Argc; } INTN GetShellArgcArgv(EFI_HANDLE ImageHandle, CHAR16 **Argv[]) { // Code inspired from EDK2's // ShellPkg/Library/UefiShellCEntryLib/UefiShellCEntryLib.c (BSD) EFI_STATUS Status; static const EFI_GUID EfiShellParametersProtocolGuid = EFI_SHELL_PARAMETERS_PROTOCOL_GUID; static const EFI_GUID ShellInterfaceProtocolGuid = SHELL_INTERFACE_PROTOCOL_GUID; EFI_SHELL_PARAMETERS_PROTOCOL *EfiShellParametersProtocol = NULL; EFI_SHELL_INTERFACE *EfiShellInterfaceProtocol = NULL; Status = uefi_call_wrapper(BS->OpenProtocol, 6, ImageHandle, (EFI_GUID*)&EfiShellParametersProtocolGuid, (VOID **)&EfiShellParametersProtocol, ImageHandle, NULL, EFI_OPEN_PROTOCOL_GET_PROTOCOL ); if (!EFI_ERROR(Status)) { // use shell 2.0 interface // Print(L"Got argc/argv from shell intf proto\n"); *Argv = EfiShellParametersProtocol->Argv; return EfiShellParametersProtocol->Argc; } // try to get shell 1.0 interface instead. Status = uefi_call_wrapper(BS->OpenProtocol, 6, ImageHandle, (EFI_GUID*)&ShellInterfaceProtocolGuid, (VOID **)&EfiShellInterfaceProtocol, ImageHandle, NULL, EFI_OPEN_PROTOCOL_GET_PROTOCOL ); if (!EFI_ERROR(Status)) { // Print(L"Got argc/argv from shell params proto\n"); *Argv = EfiShellInterfaceProtocol->Argv; return EfiShellInterfaceProtocol->Argc; } // shell 1.0 and 2.0 interfaces failed return GetShellArgcArgvFromLoadedImage(ImageHandle, Argv); }
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
/*++ Copyright (c) 1998 Intel Corporation Module Name: error.c Abstract: Revision History --*/ #include "lib.h" struct { EFI_STATUS Code; WCHAR *Desc; } ErrorCodeTable[] = { { EFI_SUCCESS, L"Success"}, { EFI_LOAD_ERROR, L"Load Error"}, { EFI_INVALID_PARAMETER, L"Invalid Parameter"}, { EFI_UNSUPPORTED, L"Unsupported"}, { EFI_BAD_BUFFER_SIZE, L"Bad Buffer Size"}, { EFI_BUFFER_TOO_SMALL, L"Buffer Too Small"}, { EFI_NOT_READY, L"Not Ready"}, { EFI_DEVICE_ERROR, L"Device Error"}, { EFI_WRITE_PROTECTED, L"Write Protected"}, { EFI_OUT_OF_RESOURCES, L"Out of Resources"}, { EFI_VOLUME_CORRUPTED, L"Volume Corrupt"}, { EFI_VOLUME_FULL, L"Volume Full"}, { EFI_NO_MEDIA, L"No Media"}, { EFI_MEDIA_CHANGED, L"Media changed"}, { EFI_NOT_FOUND, L"Not Found"}, { EFI_ACCESS_DENIED, L"Access Denied"}, { EFI_NO_RESPONSE, L"No Response"}, { EFI_NO_MAPPING, L"No mapping"}, { EFI_TIMEOUT, L"Time out"}, { EFI_NOT_STARTED, L"Not started"}, { EFI_ALREADY_STARTED, L"Already started"}, { EFI_ABORTED, L"Aborted"}, { EFI_ICMP_ERROR, L"ICMP Error"}, { EFI_TFTP_ERROR, L"TFTP Error"}, { EFI_PROTOCOL_ERROR, L"Protocol Error"}, { EFI_INCOMPATIBLE_VERSION, L"Incompatible Version"}, { EFI_SECURITY_VIOLATION, L"Security Policy Violation"}, { EFI_CRC_ERROR, L"CRC Error"}, { EFI_END_OF_MEDIA, L"End of Media"}, { EFI_END_OF_FILE, L"End of File"}, { EFI_INVALID_LANGUAGE, L"Invalid Languages"}, { EFI_COMPROMISED_DATA, L"Compromised Data"}, // warnings { EFI_WARN_UNKNOWN_GLYPH, L"Warning Unknown Glyph"}, { EFI_WARN_DELETE_FAILURE, L"Warning Delete Failure"}, { EFI_WARN_WRITE_FAILURE, L"Warning Write Failure"}, { EFI_WARN_BUFFER_TOO_SMALL, L"Warning Buffer Too Small"}, { 0, NULL} } ; VOID StatusToString ( OUT CHAR16 *Buffer, IN EFI_STATUS Status ) { UINTN Index; for (Index = 0; ErrorCodeTable[Index].Desc; Index +=1) { if (ErrorCodeTable[Index].Code == Status) { StrCpy (Buffer, ErrorCodeTable[Index].Desc); return; } } SPrint (Buffer, 0, L"%X", Status); }
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
/*++ Copyright (c) 1998 Intel Corporation Module Name: console.c Abstract: Revision History --*/ #include "lib.h" VOID Output ( IN CHAR16 *Str ) // Write a string to the console at the current cursor location { uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, Str); } VOID Input ( IN CHAR16 *Prompt OPTIONAL, OUT CHAR16 *InStr, IN UINTN StrLen ) // Input a string at the current cursor location, for StrLen { IInput ( ST->ConOut, ST->ConIn, Prompt, InStr, StrLen ); } VOID IInput ( IN SIMPLE_TEXT_OUTPUT_INTERFACE *ConOut, IN SIMPLE_INPUT_INTERFACE *ConIn, IN CHAR16 *Prompt OPTIONAL, OUT CHAR16 *InStr, IN UINTN StrLen ) // Input a string at the current cursor location, for StrLen { EFI_INPUT_KEY Key; EFI_STATUS Status; UINTN Len; if (Prompt) { ConOut->OutputString (ConOut, Prompt); } Len = 0; for (; ;) { WaitForSingleEvent (ConIn->WaitForKey, 0); Status = uefi_call_wrapper(ConIn->ReadKeyStroke, 2, ConIn, &Key); if (EFI_ERROR(Status)) { DEBUG((D_ERROR, "Input: error return from ReadKey %x\n", Status)); break; } if (Key.UnicodeChar == '\n' || Key.UnicodeChar == '\r') { break; } if (Key.UnicodeChar == '\b') { if (Len) { uefi_call_wrapper(ConOut->OutputString, 2, ConOut, L"\b \b"); Len -= 1; } continue; } if (Key.UnicodeChar >= ' ') { if (Len < StrLen-1) { InStr[Len] = Key.UnicodeChar; InStr[Len+1] = 0; uefi_call_wrapper(ConOut->OutputString, 2, ConOut, &InStr[Len]); Len += 1; } continue; } } InStr[Len] = 0; }
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
#include "lib.h" VOID Exit( IN EFI_STATUS ExitStatus, IN UINTN ExitDataSize, IN CHAR16 *ExitData OPTIONAL ) { uefi_call_wrapper(BS->Exit, 4, LibImageHandle, ExitStatus, ExitDataSize, ExitData); // Uh oh, Exit() returned?! for (;;) { } }
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
/*++ Copyright (c) 1998 Intel Corporation Module Name: hand.c Abstract: Revision History --*/ #include "lib.h" #include "efistdarg.h" // !!! EFI_STATUS LibLocateProtocol ( IN EFI_GUID *ProtocolGuid, OUT VOID **Interface ) // // Find the first instance of this Protocol in the system and return it's interface // { EFI_STATUS Status; UINTN NumberHandles, Index; EFI_HANDLE *Handles; *Interface = NULL; Status = LibLocateHandle (ByProtocol, ProtocolGuid, NULL, &NumberHandles, &Handles); if (EFI_ERROR(Status)) { DEBUG((D_INFO, "LibLocateProtocol: Handle not found\n")); return Status; } for (Index=0; Index < NumberHandles; Index++) { Status = uefi_call_wrapper(BS->HandleProtocol, 3, Handles[Index], ProtocolGuid, Interface); if (!EFI_ERROR(Status)) { break; } } if (Handles) { FreePool (Handles); } return Status; } EFI_STATUS LibLocateHandle ( IN EFI_LOCATE_SEARCH_TYPE SearchType, IN EFI_GUID *Protocol OPTIONAL, IN VOID *SearchKey OPTIONAL, IN OUT UINTN *NoHandles, OUT EFI_HANDLE **Buffer ) { EFI_STATUS Status; UINTN BufferSize; // // Initialize for GrowBuffer loop // Status = EFI_SUCCESS; *Buffer = NULL; BufferSize = 50 * sizeof(EFI_HANDLE); // // Call the real function // while (GrowBuffer (&Status, (VOID **) Buffer, BufferSize)) { Status = uefi_call_wrapper( BS->LocateHandle, 5, SearchType, Protocol, SearchKey, &BufferSize, *Buffer ); } *NoHandles = BufferSize / sizeof (EFI_HANDLE); if (EFI_ERROR(Status)) { *NoHandles = 0; } return Status; } EFI_STATUS LibLocateHandleByDiskSignature ( IN UINT8 MBRType, IN UINT8 SignatureType, IN VOID *Signature, IN OUT UINTN *NoHandles, OUT EFI_HANDLE **Buffer ) { EFI_STATUS Status; UINTN BufferSize; UINTN NoBlockIoHandles; EFI_HANDLE *BlockIoBuffer; EFI_DEVICE_PATH *DevicePath; UINTN Index; EFI_DEVICE_PATH *Next, *DevPath; HARDDRIVE_DEVICE_PATH *HardDriveDevicePath; BOOLEAN Match; BOOLEAN PreviousNodeIsHardDriveDevicePath; // // Initialize for GrowBuffer loop // Status = EFI_SUCCESS; BlockIoBuffer = NULL; BufferSize = 50 * sizeof(EFI_HANDLE); // // Call the real function // while (GrowBuffer (&Status, (VOID **)&BlockIoBuffer, BufferSize)) { // // Get list of device handles that support the BLOCK_IO Protocol. // Status = uefi_call_wrapper( BS->LocateHandle, 5, ByProtocol, &BlockIoProtocol, NULL, &BufferSize, BlockIoBuffer ); } NoBlockIoHandles = BufferSize / sizeof (EFI_HANDLE); if (EFI_ERROR(Status)) { NoBlockIoHandles = 0; } // // If there was an error or there are no device handles that support // the BLOCK_IO Protocol, then return. // if (NoBlockIoHandles == 0) { FreePool(BlockIoBuffer); *NoHandles = 0; *Buffer = NULL; return Status; } // // Loop through all the device handles that support the BLOCK_IO Protocol // *NoHandles = 0; for(Index=0;Index<NoBlockIoHandles;Index++) { Status = uefi_call_wrapper( BS->HandleProtocol, 3, BlockIoBuffer[Index], &DevicePathProtocol, (VOID*)&DevicePath ); // // Search DevicePath for a Hard Drive Media Device Path node. // If one is found, then see if it matches the signature that was // passed in. If it does match, and the next node is the End of the // device path, and the previous node is not a Hard Drive Media Device // Path, then we have found a match. // Match = FALSE; if (DevicePath != NULL) { PreviousNodeIsHardDriveDevicePath = FALSE; DevPath = DevicePath; // // Check for end of device path type // for (; ;) { if ((DevicePathType(DevPath) == MEDIA_DEVICE_PATH) && (DevicePathSubType(DevPath) == MEDIA_HARDDRIVE_DP)) { HardDriveDevicePath = (HARDDRIVE_DEVICE_PATH *)(DevPath); if (PreviousNodeIsHardDriveDevicePath == FALSE) { Next = NextDevicePathNode(DevPath); if (IsDevicePathEndType(Next)) { if ((HardDriveDevicePath->MBRType == MBRType) && (HardDriveDevicePath->SignatureType == SignatureType)) { switch(SignatureType) { case SIGNATURE_TYPE_MBR: if (*((UINT32 *)(Signature)) == *(UINT32 *)(&(HardDriveDevicePath->Signature[0]))) { Match = TRUE; } break; case SIGNATURE_TYPE_GUID: if (CompareGuid((EFI_GUID *)Signature,(EFI_GUID *)(&(HardDriveDevicePath->Signature[0]))) == 0) { Match = TRUE; } break; } } } } PreviousNodeIsHardDriveDevicePath = TRUE; } else { PreviousNodeIsHardDriveDevicePath = FALSE; } if (IsDevicePathEnd(DevPath)) { break; } DevPath = NextDevicePathNode(DevPath); } } if (Match == FALSE) { BlockIoBuffer[Index] = NULL; } else { *NoHandles = *NoHandles + 1; } } // // If there are no matches, then return // if (*NoHandles == 0) { FreePool(BlockIoBuffer); *NoHandles = 0; *Buffer = NULL; return EFI_SUCCESS; } // // Allocate space for the return buffer of device handles. // *Buffer = AllocatePool(*NoHandles * sizeof(EFI_HANDLE)); if (*Buffer == NULL) { FreePool(BlockIoBuffer); *NoHandles = 0; *Buffer = NULL; return EFI_OUT_OF_RESOURCES; } // // Build list of matching device handles. // *NoHandles = 0; for(Index=0;Index<NoBlockIoHandles;Index++) { if (BlockIoBuffer[Index] != NULL) { (*Buffer)[*NoHandles] = BlockIoBuffer[Index]; *NoHandles = *NoHandles + 1; } } FreePool(BlockIoBuffer); return EFI_SUCCESS; } EFI_FILE_HANDLE LibOpenRoot ( IN EFI_HANDLE DeviceHandle ) { EFI_STATUS Status; EFI_FILE_IO_INTERFACE *Volume; EFI_FILE_HANDLE File; // // File the file system interface to the device // Status = uefi_call_wrapper(BS->HandleProtocol, 3, DeviceHandle, &FileSystemProtocol, (VOID*)&Volume); // // Open the root directory of the volume // if (!EFI_ERROR(Status)) { Status = uefi_call_wrapper(Volume->OpenVolume, 2, Volume, &File); } // // Done // return EFI_ERROR(Status) ? NULL : File; } EFI_FILE_INFO * LibFileInfo ( IN EFI_FILE_HANDLE FHand ) { EFI_STATUS Status; EFI_FILE_INFO *Buffer; UINTN BufferSize; // // Initialize for GrowBuffer loop // Status = EFI_SUCCESS; Buffer = NULL; BufferSize = SIZE_OF_EFI_FILE_INFO + 200; // // Call the real function // while (GrowBuffer (&Status, (VOID **) &Buffer, BufferSize)) { Status = uefi_call_wrapper( FHand->GetInfo, 4, FHand, &GenericFileInfo, &BufferSize, Buffer ); } return Buffer; } EFI_FILE_SYSTEM_INFO * LibFileSystemInfo ( IN EFI_FILE_HANDLE FHand ) { EFI_STATUS Status; EFI_FILE_SYSTEM_INFO *Buffer; UINTN BufferSize; // // Initialize for GrowBuffer loop // Status = EFI_SUCCESS; Buffer = NULL; BufferSize = SIZE_OF_EFI_FILE_SYSTEM_INFO + 200; // // Call the real function // while (GrowBuffer (&Status, (VOID **) &Buffer, BufferSize)) { Status = uefi_call_wrapper( FHand->GetInfo, 4, FHand, &FileSystemInfo, &BufferSize, Buffer ); } return Buffer; } EFI_FILE_SYSTEM_VOLUME_LABEL_INFO * LibFileSystemVolumeLabelInfo ( IN EFI_FILE_HANDLE FHand ) { EFI_STATUS Status; EFI_FILE_SYSTEM_VOLUME_LABEL_INFO *Buffer; UINTN BufferSize; // // Initialize for GrowBuffer loop // Status = EFI_SUCCESS; Buffer = NULL; BufferSize = SIZE_OF_EFI_FILE_SYSTEM_VOLUME_LABEL_INFO + 200; // // Call the real function // while (GrowBuffer (&Status, (VOID **) &Buffer, BufferSize)) { Status = uefi_call_wrapper( FHand->GetInfo, 4, FHand, &FileSystemVolumeLabelInfo, &BufferSize, Buffer ); } return Buffer; } EFI_STATUS LibInstallProtocolInterfaces ( IN OUT EFI_HANDLE *Handle, ... ) { va_list args; EFI_STATUS Status; EFI_GUID *Protocol; VOID *Interface; EFI_TPL OldTpl; UINTN Index; EFI_HANDLE OldHandle; // // Syncronize with notifcations // OldTpl = uefi_call_wrapper(BS->RaiseTPL, 1, TPL_NOTIFY); OldHandle = *Handle; // // Install the protocol interfaces // Index = 0; Status = EFI_SUCCESS; va_start (args, Handle); while (!EFI_ERROR(Status)) { // // If protocol is NULL, then it's the end of the list // Protocol = va_arg(args, EFI_GUID *); if (!Protocol) { break; } Interface = va_arg(args, VOID *); // // Install it // DEBUG((D_INFO, "LibInstallProtocolInterface: %d %x\n", Protocol, Interface)); Status = uefi_call_wrapper(BS->InstallProtocolInterface, 4, Handle, Protocol, EFI_NATIVE_INTERFACE, Interface); if (EFI_ERROR(Status)) { break; } Index += 1; } // // If there was an error, remove all the interfaces that were // installed without any errors // if (EFI_ERROR(Status)) { va_start (args, Handle); while (Index) { Protocol = va_arg(args, EFI_GUID *); Interface = va_arg(args, VOID *); uefi_call_wrapper(BS->UninstallProtocolInterface, 3, *Handle, Protocol, Interface); Index -= 1; } *Handle = OldHandle; } // // Done // uefi_call_wrapper(BS->RestoreTPL, 1, OldTpl); return Status; } VOID LibUninstallProtocolInterfaces ( IN EFI_HANDLE Handle, ... ) { va_list args; EFI_STATUS Status; EFI_GUID *Protocol; VOID *Interface; va_start (args, Handle); for (; ;) { // // If protocol is NULL, then it's the end of the list // Protocol = va_arg(args, EFI_GUID *); if (!Protocol) { break; } Interface = va_arg(args, VOID *); // // Uninstall it // Status = uefi_call_wrapper(BS->UninstallProtocolInterface, 3, Handle, Protocol, Interface); if (EFI_ERROR(Status)) { DEBUG((D_ERROR, "LibUninstallProtocolInterfaces: failed %g, %r\n", Protocol, Handle)); } } } EFI_STATUS LibReinstallProtocolInterfaces ( IN OUT EFI_HANDLE *Handle, ... ) { va_list args; EFI_STATUS Status; EFI_GUID *Protocol; VOID *OldInterface, *NewInterface; EFI_TPL OldTpl; UINTN Index; // // Syncronize with notifcations // OldTpl = uefi_call_wrapper(BS->RaiseTPL, 1, TPL_NOTIFY); // // Install the protocol interfaces // Index = 0; Status = EFI_SUCCESS; va_start (args, Handle); while (!EFI_ERROR(Status)) { // // If protocol is NULL, then it's the end of the list // Protocol = va_arg(args, EFI_GUID *); if (!Protocol) { break; } OldInterface = va_arg(args, VOID *); NewInterface = va_arg(args, VOID *); // // Reinstall it // Status = uefi_call_wrapper(BS->ReinstallProtocolInterface, 4, Handle, Protocol, OldInterface, NewInterface); if (EFI_ERROR(Status)) { break; } Index += 1; } // // If there was an error, undo all the interfaces that were // reinstalled without any errors // if (EFI_ERROR(Status)) { va_start (args, Handle); while (Index) { Protocol = va_arg(args, EFI_GUID *); OldInterface = va_arg(args, VOID *); NewInterface = va_arg(args, VOID *); uefi_call_wrapper(BS->ReinstallProtocolInterface, 4, Handle, Protocol, NewInterface, OldInterface); Index -= 1; } } // // Done // uefi_call_wrapper(BS->RestoreTPL, 1, OldTpl); return Status; }
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
# # Copyright (C) 1999-2001 Hewlett-Packard Co. # Contributed by David Mosberger <[email protected]> # Contributed by Stephane Eranian <[email protected]> # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials # provided with the distribution. # * Neither the name of Hewlett-Packard Co. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND # CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, # INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS # BE LIABLE FOR ANYDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, # OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF # THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # SRCDIR = . VPATH = $(SRCDIR) include $(SRCDIR)/../Make.defaults TOPDIR = $(SRCDIR)/.. CDIR = $(TOPDIR)/.. FILES = boxdraw smbios console crc data debug dpath \ error event guid hand hw init lock \ misc print sread str cmdline \ runtime/rtlock runtime/efirtlib runtime/rtstr runtime/vm runtime/rtdata \ $(ARCH)/initplat $(ARCH)/math ifeq ($(ARCH),ia64) FILES += $(ARCH)/salpal $(ARCH)/palproc endif ifeq ($(ARCH),x86_64) FILES += $(ARCH)/callwrap $(ARCH)/efi_stub endif ifeq ($(ARCH),arm) FILES += $(ARCH)/lib1funcs $(ARCH)/div64 endif OBJS = $(FILES:%=%.o) SUBDIRS = ia32 x86_64 ia64 aarch64 arm runtime LIBDIRINSTALL = $(INSTALLROOT)$(LIBDIR) all: libsubdirs libefi.a .PHONY: libsubdirs libsubdirs: for sdir in $(SUBDIRS); do mkdir -p $$sdir; done libefi.a: $(patsubst %,libefi.a(%),$(OBJS)) clean: rm -f libefi.a *~ $(OBJS) */*.o $(LIBDIRINSTALL): mkdir -p $@ $(LIBDIRINSTALL)/libefi.a: libefi.a | $(LIBDIRINSTALL) $(INSTALL) -m 644 $< $(dir $@) install: $(LIBDIRINSTALL)/libefi.a include $(SRCDIR)/../Make.rules .PHONY: libsubdirs
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
/*++ Copyright (c) 1998 Intel Corporation Module Name: debug.c Abstract: Debug library functions Revision History --*/ #include "lib.h" // // Declare runtime functions // // // // INTN DbgAssert ( IN CONST CHAR8 *FileName, IN INTN LineNo, IN CONST CHAR8 *Description ) { DbgPrint (D_ERROR, (CHAR8 *)"%EASSERT FAILED: %a(%d): %a%N\n", FileName, LineNo, Description); BREAKPOINT(); return 0; }
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
/*++ Copyright (c) 1998 Intel Corporation Module Name: sread.c Abstract: Simple read file access Revision History --*/ #include "lib.h" #define SIMPLE_READ_SIGNATURE EFI_SIGNATURE_32('s','r','d','r') typedef struct _SIMPLE_READ_FILE { UINTN Signature; BOOLEAN FreeBuffer; VOID *Source; UINTN SourceSize; EFI_FILE_HANDLE FileHandle; } SIMPLE_READ_HANDLE; EFI_STATUS OpenSimpleReadFile ( IN BOOLEAN BootPolicy, IN VOID *SourceBuffer OPTIONAL, IN UINTN SourceSize, IN OUT EFI_DEVICE_PATH **FilePath, OUT EFI_HANDLE *DeviceHandle, OUT SIMPLE_READ_FILE *SimpleReadHandle ) /*++ Routine Description: Opens a file for (simple) reading. The simple read abstraction will access the file either from a memory copy, from a file system interface, or from the load file interface. Arguments: Returns: A handle to access the file --*/ { SIMPLE_READ_HANDLE *FHand; EFI_DEVICE_PATH *UserFilePath; EFI_DEVICE_PATH *TempFilePath; EFI_DEVICE_PATH *TempFilePathPtr; FILEPATH_DEVICE_PATH *FilePathNode; EFI_FILE_HANDLE FileHandle, LastHandle; EFI_STATUS Status; EFI_LOAD_FILE_INTERFACE *LoadFile; FHand = NULL; UserFilePath = *FilePath; // // Allocate a new simple read handle structure // FHand = AllocateZeroPool (sizeof(SIMPLE_READ_HANDLE)); if (!FHand) { Status = EFI_OUT_OF_RESOURCES; goto Done; } *SimpleReadHandle = (SIMPLE_READ_FILE) FHand; FHand->Signature = SIMPLE_READ_SIGNATURE; // // If the caller passed a copy of the file, then just use it // if (SourceBuffer) { FHand->Source = SourceBuffer; FHand->SourceSize = SourceSize; *DeviceHandle = NULL; Status = EFI_SUCCESS; goto Done; } // // Attempt to access the file via a file system interface // FileHandle = NULL; Status = uefi_call_wrapper(BS->LocateDevicePath, 3, &FileSystemProtocol, FilePath, DeviceHandle); if (!EFI_ERROR(Status)) { FileHandle = LibOpenRoot (*DeviceHandle); } Status = FileHandle ? EFI_SUCCESS : EFI_UNSUPPORTED; // // To access as a filesystem, the filepath should only // contain filepath components. Follow the filepath nodes // and find the target file // FilePathNode = (FILEPATH_DEVICE_PATH *) *FilePath; while (!IsDevicePathEnd(&FilePathNode->Header)) { // // For filesystem access each node should be a filepath component // if (DevicePathType(&FilePathNode->Header) != MEDIA_DEVICE_PATH || DevicePathSubType(&FilePathNode->Header) != MEDIA_FILEPATH_DP) { Status = EFI_UNSUPPORTED; } // // If there's been an error, stop // if (EFI_ERROR(Status)) { break; } // // Open this file path node // LastHandle = FileHandle; FileHandle = NULL; Status = uefi_call_wrapper( LastHandle->Open, 5, LastHandle, &FileHandle, FilePathNode->PathName, EFI_FILE_MODE_READ, 0 ); // // Close the last node // uefi_call_wrapper(LastHandle->Close, 1, LastHandle); // // Get the next node // FilePathNode = (FILEPATH_DEVICE_PATH *) NextDevicePathNode(&FilePathNode->Header); } // // If success, return the FHand // if (!EFI_ERROR(Status)) { ASSERT(FileHandle); FHand->FileHandle = FileHandle; goto Done; } // // Cleanup from filesystem access // if (FileHandle) { uefi_call_wrapper(FileHandle->Close, 1, FileHandle); FileHandle = NULL; *FilePath = UserFilePath; } // // If the error is something other then unsupported, return it // if (Status != EFI_UNSUPPORTED) { goto Done; } // // Attempt to access the file via the load file protocol // Status = LibDevicePathToInterface (&LoadFileProtocol, *FilePath, (VOID*)&LoadFile); if (!EFI_ERROR(Status)) { TempFilePath = DuplicateDevicePath (*FilePath); TempFilePathPtr = TempFilePath; Status = uefi_call_wrapper(BS->LocateDevicePath, 3, &LoadFileProtocol, &TempFilePath, DeviceHandle); FreePool (TempFilePathPtr); // // Determine the size of buffer needed to hold the file // SourceSize = 0; Status = uefi_call_wrapper( LoadFile->LoadFile, 5, LoadFile, *FilePath, BootPolicy, &SourceSize, NULL ); // // We expect a buffer too small error to inform us // of the buffer size needed // if (Status == EFI_BUFFER_TOO_SMALL) { SourceBuffer = AllocatePool (SourceSize); if (SourceBuffer) { FHand->FreeBuffer = TRUE; FHand->Source = SourceBuffer; FHand->SourceSize = SourceSize; Status = uefi_call_wrapper( LoadFile->LoadFile, 5, LoadFile, *FilePath, BootPolicy, &SourceSize, SourceBuffer ); } } // // If success, return FHand // if (!EFI_ERROR(Status) || Status == EFI_ALREADY_STARTED) { goto Done; } } // // Nothing else to try // DEBUG ((D_LOAD|D_WARN, "OpenSimpleReadFile: Device did not support a known load protocol\n")); Status = EFI_UNSUPPORTED; Done: // // If the file was not accessed, clean up // if (EFI_ERROR(Status) && (Status != EFI_ALREADY_STARTED)) { if (FHand) { if (FHand->FreeBuffer) { FreePool (FHand->Source); } FreePool (FHand); } } return Status; } EFI_STATUS ReadSimpleReadFile ( IN SIMPLE_READ_FILE UserHandle, IN UINTN Offset, IN OUT UINTN *ReadSize, OUT VOID *Buffer ) { UINTN EndPos; SIMPLE_READ_HANDLE *FHand; EFI_STATUS Status; FHand = UserHandle; ASSERT (FHand->Signature == SIMPLE_READ_SIGNATURE); if (FHand->Source) { // // Move data from our local copy of the file // EndPos = Offset + *ReadSize; if (EndPos > FHand->SourceSize) { *ReadSize = FHand->SourceSize - Offset; if (Offset >= FHand->SourceSize) { *ReadSize = 0; } } CopyMem (Buffer, (CHAR8 *) FHand->Source + Offset, *ReadSize); Status = EFI_SUCCESS; } else { // // Read data from the file // Status = uefi_call_wrapper(FHand->FileHandle->SetPosition, 2, FHand->FileHandle, Offset); if (!EFI_ERROR(Status)) { Status = uefi_call_wrapper(FHand->FileHandle->Read, 3, FHand->FileHandle, ReadSize, Buffer); } } return Status; } VOID CloseSimpleReadFile ( IN SIMPLE_READ_FILE UserHandle ) { SIMPLE_READ_HANDLE *FHand; FHand = UserHandle; ASSERT (FHand->Signature == SIMPLE_READ_SIGNATURE); // // Free any file handle we opened // if (FHand->FileHandle) { uefi_call_wrapper(FHand->FileHandle->Close, 1, FHand->FileHandle); } // // If we allocated the Source buffer, free it // if (FHand->FreeBuffer) { FreePool (FHand->Source); } // // Done with this simple read file handle // FreePool (FHand); }
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
/*++ Copyright (c) 1998 Intel Corporation Module Name: str.c Abstract: Revision History --*/ #include "lib.h" INTN StrCmp ( IN CONST CHAR16 *s1, IN CONST CHAR16 *s2 ) // compare strings { return RtStrCmp(s1, s2); } INTN StrnCmp ( IN CONST CHAR16 *s1, IN CONST CHAR16 *s2, IN UINTN len ) // compare strings { while (*s1 && len) { if (*s1 != *s2) { break; } s1 += 1; s2 += 1; len -= 1; } return len ? *s1 - *s2 : 0; } INTN EFIAPI LibStubStriCmp ( IN EFI_UNICODE_COLLATION_INTERFACE *This EFI_UNUSED, IN CHAR16 *s1, IN CHAR16 *s2 ) { return StrCmp (s1, s2); } VOID EFIAPI LibStubStrLwrUpr ( IN EFI_UNICODE_COLLATION_INTERFACE *This EFI_UNUSED, IN CHAR16 *Str EFI_UNUSED ) { } INTN StriCmp ( IN CONST CHAR16 *s1, IN CONST CHAR16 *s2 ) // compare strings { if (UnicodeInterface == &LibStubUnicodeInterface) return UnicodeInterface->StriColl(UnicodeInterface, (CHAR16 *)s1, (CHAR16 *)s2); else return uefi_call_wrapper(UnicodeInterface->StriColl, 3, UnicodeInterface, (CHAR16 *)s1, (CHAR16 *)s2); } VOID StrLwr ( IN CHAR16 *Str ) // lwoer case string { if (UnicodeInterface == &LibStubUnicodeInterface) UnicodeInterface->StrLwr(UnicodeInterface, Str); else uefi_call_wrapper(UnicodeInterface->StrLwr, 2, UnicodeInterface, Str); } VOID StrUpr ( IN CHAR16 *Str ) // upper case string { if (UnicodeInterface == &LibStubUnicodeInterface) UnicodeInterface->StrUpr(UnicodeInterface, Str); else uefi_call_wrapper(UnicodeInterface->StrUpr, 2, UnicodeInterface, Str); } VOID StrCpy ( IN CHAR16 *Dest, IN CONST CHAR16 *Src ) // copy strings { RtStrCpy (Dest, Src); } VOID StrnCpy ( IN CHAR16 *Dest, IN CONST CHAR16 *Src, IN UINTN Len ) // copy strings { RtStrnCpy (Dest, Src, Len); } CHAR16 * StpCpy ( IN CHAR16 *Dest, IN CONST CHAR16 *Src ) // copy strings { return RtStpCpy (Dest, Src); } CHAR16 * StpnCpy ( IN CHAR16 *Dest, IN CONST CHAR16 *Src, IN UINTN Len ) // copy strings { return RtStpnCpy (Dest, Src, Len); } VOID StrCat ( IN CHAR16 *Dest, IN CONST CHAR16 *Src ) { RtStrCat(Dest, Src); } VOID StrnCat ( IN CHAR16 *Dest, IN CONST CHAR16 *Src, IN UINTN Len ) { RtStrnCat(Dest, Src, Len); } UINTN StrnLen ( IN CONST CHAR16 *s1, IN UINTN Len ) // string length { return RtStrnLen(s1, Len); } UINTN StrLen ( IN CONST CHAR16 *s1 ) // string length { return RtStrLen(s1); } UINTN StrSize ( IN CONST CHAR16 *s1 ) // string size { return RtStrSize(s1); } CHAR16 * StrDuplicate ( IN CONST CHAR16 *Src ) // duplicate a string { CHAR16 *Dest; UINTN Size; Size = StrSize(Src); Dest = AllocatePool (Size); if (Dest) { CopyMem (Dest, Src, Size); } return Dest; } UINTN strlena ( IN CONST CHAR8 *s1 ) // string length { UINTN len; for (len=0; *s1; s1+=1, len+=1) ; return len; } UINTN strcmpa ( IN CONST CHAR8 *s1, IN CONST CHAR8 *s2 ) // compare strings { while (*s1) { if (*s1 != *s2) { break; } s1 += 1; s2 += 1; } return *s1 - *s2; } UINTN strncmpa ( IN CONST CHAR8 *s1, IN CONST CHAR8 *s2, IN UINTN len ) // compare strings { while (*s1 && len) { if (*s1 != *s2) { break; } s1 += 1; s2 += 1; len -= 1; } return len ? *s1 - *s2 : 0; } UINTN xtoi ( CONST CHAR16 *str ) // convert hex string to uint { UINTN u; CHAR16 c; // skip preceeding white space while (*str && *str == ' ') { str += 1; } // convert hex digits u = 0; while ((c = *(str++))) { if (c >= 'a' && c <= 'f') { c -= 'a' - 'A'; } if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')) { u = (u << 4) | (c - (c >= 'A' ? 'A'-10 : '0')); } else { break; } } return u; } UINTN Atoi ( CONST CHAR16 *str ) // convert hex string to uint { UINTN u; CHAR16 c; // skip preceeding white space while (*str && *str == ' ') { str += 1; } // convert digits u = 0; while ((c = *(str++))) { if (c >= '0' && c <= '9') { u = (u * 10) + c - '0'; } else { break; } } return u; } BOOLEAN MetaMatch ( IN CHAR16 *String, IN CHAR16 *Pattern ) { CHAR16 c, p, l; for (; ;) { p = *Pattern; Pattern += 1; switch (p) { case 0: // End of pattern. If end of string, TRUE match return *String ? FALSE : TRUE; case '*': // Match zero or more chars while (*String) { if (MetaMatch (String, Pattern)) { return TRUE; } String += 1; } return MetaMatch (String, Pattern); case '?': // Match any one char if (!*String) { return FALSE; } String += 1; break; case '[': // Match char set c = *String; if (!c) { return FALSE; // syntax problem } l = 0; while ((p = *Pattern++)) { if (p == ']') { return FALSE; } if (p == '-') { // if range of chars, p = *Pattern; // get high range if (p == 0 || p == ']') { return FALSE; // syntax problem } if (c >= l && c <= p) { // if in range, break; // it's a match } } l = p; if (c == p) { // if char matches break; // move on } } // skip to end of match char set while (p && p != ']') { p = *Pattern; Pattern += 1; } String += 1; break; default: c = *String; if (c != p) { return FALSE; } String += 1; break; } } } BOOLEAN EFIAPI LibStubMetaiMatch ( IN EFI_UNICODE_COLLATION_INTERFACE *This EFI_UNUSED, IN CHAR16 *String, IN CHAR16 *Pattern ) { return MetaMatch (String, Pattern); } BOOLEAN MetaiMatch ( IN CHAR16 *String, IN CHAR16 *Pattern ) { if (UnicodeInterface == &LibStubUnicodeInterface) return UnicodeInterface->MetaiMatch(UnicodeInterface, String, Pattern); else return uefi_call_wrapper(UnicodeInterface->MetaiMatch, 3, UnicodeInterface, String, Pattern); }
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
# # Copyright (C) 1999-2001 Hewlett-Packard Co. # Contributed by David Mosberger <[email protected]> # Contributed by Stephane Eranian <[email protected]> # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials # provided with the distribution. # * Neither the name of Hewlett-Packard Co. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND # CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, # INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS # BE LIABLE FOR ANYDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, # OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF # THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # SRCDIR = . VPATH = $(SRCDIR) include $(SRCDIR)/../Make.defaults TOPDIR = $(SRCDIR)/.. CDIR = $(TOPDIR)/.. FILES = boxdraw smbios console crc data debug dpath \ error event exit guid hand hw init lock \ misc print sread str cmdline \ runtime/rtlock runtime/efirtlib runtime/rtstr runtime/vm runtime/rtdata \ $(ARCH)/initplat $(ARCH)/math $(ARCH)/setjmp ifeq ($(ARCH),ia64) FILES += $(ARCH)/salpal $(ARCH)/palproc endif ifeq ($(ARCH),x86_64) FILES += $(ARCH)/callwrap $(ARCH)/efi_stub endif ifeq ($(ARCH),arm) FILES += $(ARCH)/uldiv $(ARCH)/ldivmod $(ARCH)/div $(ARCH)/llsl $(ARCH)/llsr \ $(ARCH)/mullu endif OBJS = $(FILES:%=%.o) SUBDIRS = ia32 x86_64 ia64 aarch64 arm mips64el runtime LIBDIRINSTALL = $(INSTALLROOT)$(LIBDIR) all: libsubdirs libefi.a .PHONY: libsubdirs libsubdirs: for sdir in $(SUBDIRS); do mkdir -p $$sdir; done libefi.a: $(OBJS) $(AR) $(ARFLAGS) $@ $^ clean: rm -f libefi.a *~ $(OBJS) */*.o $(LIBDIRINSTALL): mkdir -p $@ $(LIBDIRINSTALL)/libefi.a: libefi.a | $(LIBDIRINSTALL) $(INSTALL) -m 644 $< $(dir $@) install: $(LIBDIRINSTALL)/libefi.a include $(SRCDIR)/../Make.rules .PHONY: libsubdirs
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
/*++ Copyright (c) 1998 Intel Corporation Module Name: lib.h Abstract: EFI library header files Revision History --*/ #ifdef __GNUC__ #pragma GCC visibility push(hidden) #endif #include "efi.h" #include "efilib.h" #include "efirtlib.h" // // Include non architectural protocols // #include "efivar.h" #include "legacyboot.h" #include "intload.h" #include "vgaclass.h" #include "eficonsplit.h" #include "adapterdebug.h" #include "intload.h" #include "efigpt.h" #include "libsmbios.h" // // Prototypes // VOID InitializeGuid ( VOID ); INTN EFIAPI LibStubStriCmp ( IN EFI_UNICODE_COLLATION_INTERFACE *This, IN CHAR16 *S1, IN CHAR16 *S2 ); BOOLEAN EFIAPI LibStubMetaiMatch ( IN EFI_UNICODE_COLLATION_INTERFACE *This, IN CHAR16 *String, IN CHAR16 *Pattern ); VOID EFIAPI LibStubStrLwrUpr ( IN EFI_UNICODE_COLLATION_INTERFACE *This, IN CHAR16 *Str ); BOOLEAN LibMatchDevicePaths ( IN EFI_DEVICE_PATH *Multi, IN EFI_DEVICE_PATH *Single ); EFI_DEVICE_PATH * LibDuplicateDevicePathInstance ( IN EFI_DEVICE_PATH *DevPath ); // // Globals // extern BOOLEAN LibInitialized; extern BOOLEAN LibFwInstance; extern EFI_HANDLE LibImageHandle; extern SIMPLE_TEXT_OUTPUT_INTERFACE *LibRuntimeDebugOut; extern EFI_UNICODE_COLLATION_INTERFACE *UnicodeInterface; extern EFI_UNICODE_COLLATION_INTERFACE LibStubUnicodeInterface; extern EFI_RAISE_TPL LibRuntimeRaiseTPL; extern EFI_RESTORE_TPL LibRuntimeRestoreTPL;
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
/*++ Copyright (c) 1998 Intel Corporation Module Name: data.c Abstract: EFI library global data Revision History --*/ #include "lib.h" // // LibInitialized - TRUE once InitializeLib() is called for the first time // BOOLEAN LibInitialized = FALSE; // // ImageHandle - Current ImageHandle, as passed to InitializeLib // EFI_HANDLE LibImageHandle; // // ST - pointer to the EFI system table // EFI_SYSTEM_TABLE *ST; // // BS - pointer to the boot services table // EFI_BOOT_SERVICES *BS; // // Default pool allocation type // EFI_MEMORY_TYPE PoolAllocationType = EfiBootServicesData; // // Unicode collation functions that are in use // EFI_UNICODE_COLLATION_INTERFACE LibStubUnicodeInterface = { LibStubStriCmp, LibStubMetaiMatch, LibStubStrLwrUpr, LibStubStrLwrUpr, NULL, // FatToStr NULL, // StrToFat NULL // SupportedLanguages }; EFI_UNICODE_COLLATION_INTERFACE *UnicodeInterface = &LibStubUnicodeInterface; // // Root device path // EFI_DEVICE_PATH RootDevicePath[] = { {END_DEVICE_PATH_TYPE, END_ENTIRE_DEVICE_PATH_SUBTYPE, {END_DEVICE_PATH_LENGTH,0}} }; EFI_DEVICE_PATH EndDevicePath[] = { {END_DEVICE_PATH_TYPE, END_ENTIRE_DEVICE_PATH_SUBTYPE, {END_DEVICE_PATH_LENGTH, 0}} }; EFI_DEVICE_PATH EndInstanceDevicePath[] = { {END_DEVICE_PATH_TYPE, END_INSTANCE_DEVICE_PATH_SUBTYPE, {END_DEVICE_PATH_LENGTH, 0}} }; // // EFI IDs // EFI_GUID gEfiGlobalVariableGuid = EFI_GLOBAL_VARIABLE; EFI_GUID NullGuid = { 0,0,0,{0,0,0,0,0,0,0,0} }; // // Protocol IDs // EFI_GUID gEfiDevicePathProtocolGuid = EFI_DEVICE_PATH_PROTOCOL_GUID; EFI_GUID gEfiDevicePathToTextProtocolGuid = EFI_DEVICE_PATH_TO_TEXT_PROTOCOL_GUID; EFI_GUID gEfiDevicePathFromTextProtocolGuid = EFI_DEVICE_PATH_FROM_TEXT_PROTOCOL_GUID; EFI_GUID gEfiLoadedImageProtocolGuid = EFI_LOADED_IMAGE_PROTOCOL_GUID; EFI_GUID gEfiSimpleTextInProtocolGuid = EFI_SIMPLE_TEXT_INPUT_PROTOCOL_GUID; EFI_GUID gEfiSimpleTextOutProtocolGuid = EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL_GUID; EFI_GUID gEfiBlockIoProtocolGuid = EFI_BLOCK_IO_PROTOCOL_GUID; EFI_GUID gEfiBlockIo2ProtocolGuid = EFI_BLOCK_IO2_PROTOCOL_GUID; EFI_GUID gEfiDiskIoProtocolGuid = EFI_DISK_IO_PROTOCOL_GUID; EFI_GUID gEfiDiskIo2ProtocolGuid = EFI_DISK_IO2_PROTOCOL_GUID; EFI_GUID gEfiSimpleFileSystemProtocolGuid = EFI_SIMPLE_FILE_SYSTEM_PROTOCOL_GUID; EFI_GUID gEfiLoadFileProtocolGuid = EFI_LOAD_FILE_PROTOCOL_GUID; EFI_GUID gEfiDeviceIoProtocolGuid = EFI_DEVICE_IO_PROTOCOL_GUID; EFI_GUID gEfiUnicodeCollationProtocolGuid = EFI_UNICODE_COLLATION_PROTOCOL_GUID; EFI_GUID gEfiSerialIoProtocolGuid = EFI_SERIAL_IO_PROTOCOL_GUID; EFI_GUID gEfiSimpleNetworkProtocolGuid = EFI_SIMPLE_NETWORK_PROTOCOL_GUID; EFI_GUID gEfiPxeBaseCodeProtocolGuid = EFI_PXE_BASE_CODE_PROTOCOL_GUID; EFI_GUID gEfiPxeBaseCodeCallbackProtocolGuid = EFI_PXE_BASE_CODE_CALLBACK_PROTOCOL_GUID; EFI_GUID gEfiNetworkInterfaceIdentifierProtocolGuid = EFI_NETWORK_INTERFACE_IDENTIFIER_PROTOCOL_GUID; EFI_GUID gEFiUiInterfaceProtocolGuid = EFI_UI_INTERFACE_PROTOCOL_GUID; EFI_GUID gEfiPciIoProtocolGuid = EFI_PCI_IO_PROTOCOL_GUID; EFI_GUID gEfiPciRootBridgeIoProtocolGuid = EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_GUID; EFI_GUID gEfiDriverBindingProtocolGuid = EFI_DRIVER_BINDING_PROTOCOL_GUID; EFI_GUID gEfiComponentNameProtocolGuid = EFI_COMPONENT_NAME_PROTOCOL_GUID; EFI_GUID gEfiComponentName2ProtocolGuid = EFI_COMPONENT_NAME2_PROTOCOL_GUID; EFI_GUID gEfiHashProtocolGuid = EFI_HASH_PROTOCOL_GUID; EFI_GUID gEfiPlatformDriverOverrideProtocolGuid = EFI_PLATFORM_DRIVER_OVERRIDE_PROTOCOL_GUID; EFI_GUID gEfiBusSpecificDriverOverrideProtocolGuid = EFI_BUS_SPECIFIC_DRIVER_OVERRIDE_PROTOCOL_GUID; EFI_GUID gEfiDriverFamilyOverrideProtocolGuid = EFI_DRIVER_FAMILY_OVERRIDE_PROTOCOL_GUID; EFI_GUID gEfiEbcProtocolGuid = EFI_EBC_PROTOCOL_GUID; // // File system information IDs // EFI_GUID gEfiFileInfoGuid = EFI_FILE_INFO_ID; EFI_GUID gEfiFileSystemInfoGuid = EFI_FILE_SYSTEM_INFO_ID; EFI_GUID gEfiFileSystemVolumeLabelInfoIdGuid = EFI_FILE_SYSTEM_VOLUME_LABEL_INFO_ID; // // Reference implementation public protocol IDs // EFI_GUID InternalShellProtocol = INTERNAL_SHELL_GUID; EFI_GUID VariableStoreProtocol = VARIABLE_STORE_PROTOCOL; EFI_GUID LegacyBootProtocol = LEGACY_BOOT_PROTOCOL; EFI_GUID VgaClassProtocol = VGA_CLASS_DRIVER_PROTOCOL; EFI_GUID TextOutSpliterProtocol = TEXT_OUT_SPLITER_PROTOCOL; EFI_GUID ErrorOutSpliterProtocol = ERROR_OUT_SPLITER_PROTOCOL; EFI_GUID TextInSpliterProtocol = TEXT_IN_SPLITER_PROTOCOL; /* Added for GOP support */ EFI_GUID gEfiGraphicsOutputProtocolGuid = EFI_GRAPHICS_OUTPUT_PROTOCOL_GUID; EFI_GUID gEfiEdidDiscoveredProtocolGuid = EFI_EDID_DISCOVERED_PROTOCOL_GUID; EFI_GUID gEfiEdidActiveProtocolGuid = EFI_EDID_ACTIVE_PROTOCOL_GUID; EFI_GUID gEfiEdidOverrideProtocolGuid = EFI_EDID_OVERRIDE_PROTOCOL_GUID; EFI_GUID AdapterDebugProtocol = ADAPTER_DEBUG_PROTOCOL; // // Device path media protocol IDs // EFI_GUID gEfiPcAnsiGuid = EFI_PC_ANSI_GUID; EFI_GUID gEfiVT100Guid = EFI_VT_100_GUID; EFI_GUID gEfiVT100PlusGuid = EFI_VT_100_PLUS_GUID; EFI_GUID gEfiVTUTF8Guid = EFI_VT_UTF8_GUID; // // EFI GPT Partition Type GUIDs // EFI_GUID EfiPartTypeSystemPartitionGuid = EFI_PART_TYPE_EFI_SYSTEM_PART_GUID; EFI_GUID EfiPartTypeLegacyMbrGuid = EFI_PART_TYPE_LEGACY_MBR_GUID; // // Reference implementation Vendor Device Path Guids // EFI_GUID UnknownDevice = UNKNOWN_DEVICE_GUID; // // Configuration Table GUIDs // EFI_GUID MpsTableGuid = MPS_TABLE_GUID; EFI_GUID AcpiTableGuid = ACPI_TABLE_GUID; EFI_GUID SMBIOSTableGuid = SMBIOS_TABLE_GUID; EFI_GUID SMBIOS3TableGuid = SMBIOS3_TABLE_GUID; EFI_GUID SalSystemTableGuid = SAL_SYSTEM_TABLE_GUID; // // Network protocol GUIDs // EFI_GUID Ip4ServiceBindingProtocol = EFI_IP4_SERVICE_BINDING_PROTOCOL; EFI_GUID Ip4Protocol = EFI_IP4_PROTOCOL; EFI_GUID Udp4ServiceBindingProtocol = EFI_UDP4_SERVICE_BINDING_PROTOCOL; EFI_GUID Udp4Protocol = EFI_UDP4_PROTOCOL; EFI_GUID Tcp4ServiceBindingProtocol = EFI_TCP4_SERVICE_BINDING_PROTOCOL; EFI_GUID Tcp4Protocol = EFI_TCP4_PROTOCOL; // // Pointer protocol GUIDs // EFI_GUID SimplePointerProtocol = EFI_SIMPLE_POINTER_PROTOCOL_GUID; EFI_GUID AbsolutePointerProtocol = EFI_ABSOLUTE_POINTER_PROTOCOL_GUID; // // Debugger protocol GUIDs // EFI_GUID gEfiDebugImageInfoTableGuid = EFI_DEBUG_IMAGE_INFO_TABLE_GUID; EFI_GUID gEfiDebugSupportProtocolGuid = EFI_DEBUG_SUPPORT_PROTOCOL_GUID;
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
/*++ Copyright (c) 1998 Intel Corporation Module Name: misc.c Abstract: Misc EFI support functions Revision History --*/ #include "lib.h" // // Additional Known guids // #define SHELL_INTERFACE_PROTOCOL \ { 0x47c7b223, 0xc42a, 0x11d2, {0x8e, 0x57, 0x0, 0xa0, 0xc9, 0x69, 0x72, 0x3b} } #define ENVIRONMENT_VARIABLE_ID \ { 0x47c7b224, 0xc42a, 0x11d2, {0x8e, 0x57, 0x0, 0xa0, 0xc9, 0x69, 0x72, 0x3b} } #define DEVICE_PATH_MAPPING_ID \ { 0x47c7b225, 0xc42a, 0x11d2, {0x8e, 0x57, 0x0, 0xa0, 0xc9, 0x69, 0x72, 0x3b} } #define PROTOCOL_ID_ID \ { 0x47c7b226, 0xc42a, 0x11d2, {0x8e, 0x57, 0x0, 0xa0, 0xc9, 0x69, 0x72, 0x3b} } #define ALIAS_ID \ { 0x47c7b227, 0xc42a, 0x11d2, {0x8e, 0x57, 0x0, 0xa0, 0xc9, 0x69, 0x72, 0x3b} } static EFI_GUID ShellInterfaceProtocol = SHELL_INTERFACE_PROTOCOL; static EFI_GUID SEnvId = ENVIRONMENT_VARIABLE_ID; static EFI_GUID SMapId = DEVICE_PATH_MAPPING_ID; static EFI_GUID SProtId = PROTOCOL_ID_ID; static EFI_GUID SAliasId = ALIAS_ID; static struct { EFI_GUID *Guid; WCHAR *GuidName; } KnownGuids[] = { { &NullGuid, L"G0" }, { &gEfiGlobalVariableGuid, L"EfiVar" }, { &VariableStoreProtocol, L"VarStore" }, { &gEfiDevicePathProtocolGuid, L"DevPath" }, { &gEfiLoadedImageProtocolGuid, L"LdImg" }, { &gEfiSimpleTextInProtocolGuid, L"TxtIn" }, { &gEfiSimpleTextOutProtocolGuid, L"TxtOut" }, { &gEfiBlockIoProtocolGuid, L"BlkIo" }, { &gEfiBlockIo2ProtocolGuid, L"BlkIo2" }, { &gEfiDiskIoProtocolGuid, L"DskIo" }, { &gEfiDiskIo2ProtocolGuid, L"DskIo2" }, { &gEfiSimpleFileSystemProtocolGuid, L"Fs" }, { &gEfiLoadFileProtocolGuid, L"LdFile" }, { &gEfiDeviceIoProtocolGuid, L"DevIo" }, { &gEfiComponentNameProtocolGuid, L"CName" }, { &gEfiComponentName2ProtocolGuid, L"CName2" }, { &gEfiFileInfoGuid, L"FileInfo" }, { &gEfiFileSystemInfoGuid, L"FsInfo" }, { &gEfiFileSystemVolumeLabelInfoIdGuid, L"FsVolInfo" }, { &gEfiUnicodeCollationProtocolGuid, L"Unicode" }, { &LegacyBootProtocol, L"LegacyBoot" }, { &gEfiSerialIoProtocolGuid, L"SerIo" }, { &VgaClassProtocol, L"VgaClass"}, { &gEfiSimpleNetworkProtocolGuid, L"Net" }, { &gEfiNetworkInterfaceIdentifierProtocolGuid, L"Nii" }, { &gEfiPxeBaseCodeProtocolGuid, L"Pxe" }, { &gEfiPxeBaseCodeCallbackProtocolGuid, L"PxeCb" }, { &TextOutSpliterProtocol, L"TxtOutSplit" }, { &ErrorOutSpliterProtocol, L"ErrOutSplit" }, { &TextInSpliterProtocol, L"TxtInSplit" }, { &gEfiPcAnsiGuid, L"PcAnsi" }, { &gEfiVT100Guid, L"Vt100" }, { &gEfiVT100PlusGuid, L"Vt100Plus" }, { &gEfiVTUTF8Guid, L"VtUtf8" }, { &UnknownDevice, L"UnknownDev" }, { &EfiPartTypeSystemPartitionGuid, L"ESP" }, { &EfiPartTypeLegacyMbrGuid, L"GPT MBR" }, { &ShellInterfaceProtocol, L"ShellInt" }, { &SEnvId, L"SEnv" }, { &SProtId, L"ShellProtId" }, { &SMapId, L"ShellDevPathMap" }, { &SAliasId, L"ShellAlias" }, { NULL, L"" } }; // // // LIST_ENTRY GuidList; VOID InitializeGuid ( VOID ) { } INTN CompareGuid( IN EFI_GUID *Guid1, IN EFI_GUID *Guid2 ) /*++ Routine Description: Compares to GUIDs Arguments: Guid1 - guid to compare Guid2 - guid to compare Returns: = 0 if Guid1 == Guid2 --*/ { return RtCompareGuid (Guid1, Guid2); } VOID GuidToString ( OUT CHAR16 *Buffer, IN EFI_GUID *Guid ) { UINTN Index; // // Else, (for now) use additional internal function for mapping guids // for (Index=0; KnownGuids[Index].Guid; Index++) { if (CompareGuid(Guid, KnownGuids[Index].Guid) == 0) { SPrint (Buffer, 0, KnownGuids[Index].GuidName); return ; } } // // Else dump it // SPrint (Buffer, 0, L"%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x", Guid->Data1, Guid->Data2, Guid->Data3, Guid->Data4[0], Guid->Data4[1], Guid->Data4[2], Guid->Data4[3], Guid->Data4[4], Guid->Data4[5], Guid->Data4[6], Guid->Data4[7] ); }
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
/*++ Copyright (c) 1998 Intel Corporation Module Name: dpath.c Abstract: MBR & Device Path functions Revision History 2014/04 B.Burette - updated device path text representation, conforming to UEFI specification 2.4 (dec. 2013). More specifically: - § 9.3.5: added some media types ie. Sata() - § 9.6.1.2: Acpi(PNP0A03,0) makes more sense when displayed as PciRoot(0) - § 9.6.1.5: use commas (instead of '|') between option specific parameters - § 9.6.1.6: hex values in device paths must be preceded by "0x" or "0X" --*/ #include "lib.h" #define ALIGN_SIZE(a) ((a % MIN_ALIGNMENT_SIZE) ? MIN_ALIGNMENT_SIZE - (a % MIN_ALIGNMENT_SIZE) : 0) EFI_DEVICE_PATH * DevicePathFromHandle ( IN EFI_HANDLE Handle ) { EFI_STATUS Status; EFI_DEVICE_PATH *DevicePath; Status = uefi_call_wrapper(BS->HandleProtocol, 3, Handle, &DevicePathProtocol, (VOID*)&DevicePath); if (EFI_ERROR(Status)) { DevicePath = NULL; } return DevicePath; } EFI_DEVICE_PATH * DevicePathInstance ( IN OUT EFI_DEVICE_PATH **DevicePath, OUT UINTN *Size ) { EFI_DEVICE_PATH *Start, *Next, *DevPath; UINTN Count; DevPath = *DevicePath; Start = DevPath; if (!DevPath) { return NULL; } // // Check for end of device path type // for (Count = 0; ; Count++) { Next = NextDevicePathNode(DevPath); if (IsDevicePathEndType(DevPath)) { break; } if (Count > 01000) { // // BugBug: Debug code to catch bogus device paths // DEBUG((D_ERROR, "DevicePathInstance: DevicePath %x Size %d", *DevicePath, ((UINT8 *) DevPath) - ((UINT8 *) Start) )); DumpHex (0, 0, ((UINT8 *) DevPath) - ((UINT8 *) Start), Start); break; } DevPath = Next; } ASSERT (DevicePathSubType(DevPath) == END_ENTIRE_DEVICE_PATH_SUBTYPE || DevicePathSubType(DevPath) == END_INSTANCE_DEVICE_PATH_SUBTYPE); // // Set next position // if (DevicePathSubType(DevPath) == END_ENTIRE_DEVICE_PATH_SUBTYPE) { Next = NULL; } *DevicePath = Next; // // Return size and start of device path instance // *Size = ((UINT8 *) DevPath) - ((UINT8 *) Start); return Start; } UINTN DevicePathInstanceCount ( IN EFI_DEVICE_PATH *DevicePath ) { UINTN Count, Size; Count = 0; while (DevicePathInstance(&DevicePath, &Size)) { Count += 1; } return Count; } EFI_DEVICE_PATH * AppendDevicePath ( IN EFI_DEVICE_PATH *Src1, IN EFI_DEVICE_PATH *Src2 ) // Src1 may have multiple "instances" and each instance is appended // Src2 is appended to each instance is Src1. (E.g., it's possible // to append a new instance to the complete device path by passing // it in Src2) { UINTN Src1Size, Src1Inst, Src2Size, Size; EFI_DEVICE_PATH *Dst, *Inst; UINT8 *DstPos; // // If there's only 1 path, just duplicate it // if (!Src1) { ASSERT (!IsDevicePathUnpacked (Src2)); return DuplicateDevicePath (Src2); } if (!Src2) { ASSERT (!IsDevicePathUnpacked (Src1)); return DuplicateDevicePath (Src1); } // // Verify we're not working with unpacked paths // // ASSERT (!IsDevicePathUnpacked (Src1)); // ASSERT (!IsDevicePathUnpacked (Src2)); // // Append Src2 to every instance in Src1 // Src1Size = DevicePathSize(Src1); Src1Inst = DevicePathInstanceCount(Src1); Src2Size = DevicePathSize(Src2); Size = Src1Size * Src1Inst + Src2Size; Dst = AllocatePool (Size); if (Dst) { DstPos = (UINT8 *) Dst; // // Copy all device path instances // while ((Inst = DevicePathInstance (&Src1, &Size))) { CopyMem(DstPos, Inst, Size); DstPos += Size; CopyMem(DstPos, Src2, Src2Size); DstPos += Src2Size; CopyMem(DstPos, EndInstanceDevicePath, sizeof(EFI_DEVICE_PATH)); DstPos += sizeof(EFI_DEVICE_PATH); } // Change last end marker DstPos -= sizeof(EFI_DEVICE_PATH); CopyMem(DstPos, EndDevicePath, sizeof(EFI_DEVICE_PATH)); } return Dst; } EFI_DEVICE_PATH * AppendDevicePathNode ( IN EFI_DEVICE_PATH *Src1, IN EFI_DEVICE_PATH *Src2 ) // Src1 may have multiple "instances" and each instance is appended // Src2 is a signal device path node (without a terminator) that is // appended to each instance is Src1. { EFI_DEVICE_PATH *Temp, *Eop; UINTN Length; // // Build a Src2 that has a terminator on it // Length = DevicePathNodeLength(Src2); Temp = AllocatePool (Length + sizeof(EFI_DEVICE_PATH)); if (!Temp) { return NULL; } CopyMem (Temp, Src2, Length); Eop = NextDevicePathNode(Temp); SetDevicePathEndNode(Eop); // // Append device paths // Src1 = AppendDevicePath (Src1, Temp); FreePool (Temp); return Src1; } EFI_DEVICE_PATH * FileDevicePath ( IN EFI_HANDLE Device OPTIONAL, IN CHAR16 *FileName ) /*++ N.B. Results are allocated from pool. The caller must FreePool the resulting device path structure --*/ { UINTN Size; FILEPATH_DEVICE_PATH *FilePath; EFI_DEVICE_PATH *Eop, *DevicePath; Size = StrSize(FileName); FilePath = AllocateZeroPool (Size + SIZE_OF_FILEPATH_DEVICE_PATH + sizeof(EFI_DEVICE_PATH)); DevicePath = NULL; if (FilePath) { // // Build a file path // FilePath->Header.Type = MEDIA_DEVICE_PATH; FilePath->Header.SubType = MEDIA_FILEPATH_DP; SetDevicePathNodeLength (&FilePath->Header, Size + SIZE_OF_FILEPATH_DEVICE_PATH); CopyMem (FilePath->PathName, FileName, Size); Eop = NextDevicePathNode(&FilePath->Header); SetDevicePathEndNode(Eop); // // Append file path to device's device path // DevicePath = (EFI_DEVICE_PATH *) FilePath; if (Device) { DevicePath = AppendDevicePath ( DevicePathFromHandle(Device), DevicePath ); FreePool(FilePath); } } return DevicePath; } UINTN DevicePathSize ( IN EFI_DEVICE_PATH *DevPath ) { EFI_DEVICE_PATH *Start; // // Search for the end of the device path structure // Start = DevPath; while (!IsDevicePathEnd(DevPath)) { DevPath = NextDevicePathNode(DevPath); } // // Compute the size // return ((UINTN) DevPath - (UINTN) Start) + sizeof(EFI_DEVICE_PATH); } EFI_DEVICE_PATH * DuplicateDevicePath ( IN EFI_DEVICE_PATH *DevPath ) { EFI_DEVICE_PATH *NewDevPath; UINTN Size; // // Compute the size // Size = DevicePathSize (DevPath); // // Make a copy // NewDevPath = AllocatePool (Size); if (NewDevPath) { CopyMem (NewDevPath, DevPath, Size); } return NewDevPath; } EFI_DEVICE_PATH * UnpackDevicePath ( IN EFI_DEVICE_PATH *DevPath ) { EFI_DEVICE_PATH *Src, *Dest, *NewPath; UINTN Size; // // Walk device path and round sizes to valid boundries // Src = DevPath; Size = 0; for (; ;) { Size += DevicePathNodeLength(Src); Size += ALIGN_SIZE(Size); if (IsDevicePathEnd(Src)) { break; } Src = NextDevicePathNode(Src); } // // Allocate space for the unpacked path // NewPath = AllocateZeroPool (Size); if (NewPath) { ASSERT (((UINTN)NewPath) % MIN_ALIGNMENT_SIZE == 0); // // Copy each node // Src = DevPath; Dest = NewPath; for (; ;) { Size = DevicePathNodeLength(Src); CopyMem (Dest, Src, Size); Size += ALIGN_SIZE(Size); SetDevicePathNodeLength (Dest, Size); Dest->Type |= EFI_DP_TYPE_UNPACKED; Dest = (EFI_DEVICE_PATH *) (((UINT8 *) Dest) + Size); if (IsDevicePathEnd(Src)) { break; } Src = NextDevicePathNode(Src); } } return NewPath; } EFI_DEVICE_PATH* AppendDevicePathInstance ( IN EFI_DEVICE_PATH *Src, IN EFI_DEVICE_PATH *Instance ) { UINT8 *Ptr; EFI_DEVICE_PATH *DevPath; UINTN SrcSize; UINTN InstanceSize; if (Src == NULL) { return DuplicateDevicePath (Instance); } SrcSize = DevicePathSize(Src); InstanceSize = DevicePathSize(Instance); Ptr = AllocatePool (SrcSize + InstanceSize); DevPath = (EFI_DEVICE_PATH *)Ptr; ASSERT(DevPath); CopyMem (Ptr, Src, SrcSize); // FreePool (Src); while (!IsDevicePathEnd(DevPath)) { DevPath = NextDevicePathNode(DevPath); } // // Convert the End to an End Instance, since we are // appending another instacne after this one its a good // idea. // DevPath->SubType = END_INSTANCE_DEVICE_PATH_SUBTYPE; DevPath = NextDevicePathNode(DevPath); CopyMem (DevPath, Instance, InstanceSize); return (EFI_DEVICE_PATH *)Ptr; } EFI_STATUS LibDevicePathToInterface ( IN EFI_GUID *Protocol, IN EFI_DEVICE_PATH *FilePath, OUT VOID **Interface ) { EFI_STATUS Status; EFI_HANDLE Device; Status = uefi_call_wrapper(BS->LocateDevicePath, 3, Protocol, &FilePath, &Device); if (!EFI_ERROR(Status)) { // If we didn't get a direct match return not found Status = EFI_NOT_FOUND; if (IsDevicePathEnd(FilePath)) { // // It was a direct match, lookup the protocol interface // Status =uefi_call_wrapper(BS->HandleProtocol, 3, Device, Protocol, Interface); } } // // If there was an error, do not return an interface // if (EFI_ERROR(Status)) { *Interface = NULL; } return Status; } static VOID _DevPathPci ( IN OUT POOL_PRINT *Str, IN VOID *DevPath ) { PCI_DEVICE_PATH *Pci; Pci = DevPath; CatPrint(Str, L"Pci(0x%x,0x%x)", Pci->Device, Pci->Function); } static VOID _DevPathPccard ( IN OUT POOL_PRINT *Str, IN VOID *DevPath ) { PCCARD_DEVICE_PATH *Pccard; Pccard = DevPath; CatPrint(Str, L"Pccard(0x%x)", Pccard-> FunctionNumber ); } static VOID _DevPathMemMap ( IN OUT POOL_PRINT *Str, IN VOID *DevPath ) { MEMMAP_DEVICE_PATH *MemMap; MemMap = DevPath; CatPrint(Str, L"MemMap(%d,0x%x,0x%x)", MemMap->MemoryType, MemMap->StartingAddress, MemMap->EndingAddress ); } static VOID _DevPathController ( IN OUT POOL_PRINT *Str, IN VOID *DevPath ) { CONTROLLER_DEVICE_PATH *Controller; Controller = DevPath; CatPrint(Str, L"Ctrl(%d)", Controller->Controller ); } static VOID _DevPathVendor ( IN OUT POOL_PRINT *Str, IN VOID *DevPath ) { VENDOR_DEVICE_PATH *Vendor; CHAR16 *Type; UNKNOWN_DEVICE_VENDOR_DEVICE_PATH *UnknownDevPath; Vendor = DevPath; switch (DevicePathType(&Vendor->Header)) { case HARDWARE_DEVICE_PATH: Type = L"Hw"; break; case MESSAGING_DEVICE_PATH: Type = L"Msg"; break; case MEDIA_DEVICE_PATH: Type = L"Media"; break; default: Type = L"?"; break; } CatPrint(Str, L"Ven%s(%g", Type, &Vendor->Guid); if (CompareGuid (&Vendor->Guid, &UnknownDevice) == 0) { // // GUID used by EFI to enumerate an EDD 1.1 device // UnknownDevPath = (UNKNOWN_DEVICE_VENDOR_DEVICE_PATH *)Vendor; CatPrint(Str, L":%02x)", UnknownDevPath->LegacyDriveLetter); } else { CatPrint(Str, L")"); } } /* Type: 2 (ACPI Device Path) SubType: 1 (ACPI Device Path) */ static VOID _DevPathAcpi ( IN OUT POOL_PRINT *Str, IN VOID *DevPath ) { ACPI_HID_DEVICE_PATH *Acpi; Acpi = DevPath; if ((Acpi->HID & PNP_EISA_ID_MASK) == PNP_EISA_ID_CONST) { switch ( EISA_ID_TO_NUM( Acpi-> HID ) ) { case 0x301 : { CatPrint( Str , L"Keyboard(%d)" , Acpi-> UID ) ; break ; } case 0x401 : { CatPrint( Str , L"ParallelPort(%d)" , Acpi-> UID ) ; break ; } case 0x501 : { CatPrint( Str , L"Serial(%d)" , Acpi-> UID ) ; break ; } case 0x604 : { CatPrint( Str , L"Floppy(%d)" , Acpi-> UID ) ; break ; } case 0xa03 : { CatPrint( Str , L"PciRoot(%d)" , Acpi-> UID ) ; break ; } case 0xa08 : { CatPrint( Str , L"PcieRoot(%d)" , Acpi-> UID ) ; break ; } default : { CatPrint( Str , L"Acpi(PNP%04x" , EISA_ID_TO_NUM( Acpi-> HID ) ) ; if ( Acpi-> UID ) CatPrint( Str , L",%d" , Acpi-> UID ) ; CatPrint( Str , L")" ) ; break ; } } } else { CatPrint( Str , L"Acpi(0x%X" , Acpi-> HID ) ; if ( Acpi-> UID ) CatPrint( Str , L",%d" , Acpi-> UID ) ; CatPrint( Str , L")" , Acpi-> HID , Acpi-> UID ) ; } } static VOID _DevPathAtapi ( IN OUT POOL_PRINT *Str, IN VOID *DevPath ) { ATAPI_DEVICE_PATH *Atapi; Atapi = DevPath; CatPrint(Str, L"Ata(%s,%s)", Atapi->PrimarySecondary ? L"Secondary" : L"Primary", Atapi->SlaveMaster ? L"Slave" : L"Master" ); } static VOID _DevPathScsi ( IN OUT POOL_PRINT *Str, IN VOID *DevPath ) { SCSI_DEVICE_PATH *Scsi; Scsi = DevPath; CatPrint(Str, L"Scsi(%d,%d)", Scsi->Pun, Scsi->Lun); } static VOID _DevPathFibre ( IN OUT POOL_PRINT *Str, IN VOID *DevPath ) { FIBRECHANNEL_DEVICE_PATH *Fibre; Fibre = DevPath; CatPrint( Str , L"Fibre%s(0x%016lx,0x%016lx)" , DevicePathType( & Fibre-> Header ) == MSG_FIBRECHANNEL_DP ? L"" : L"Ex" , Fibre-> WWN , Fibre-> Lun ) ; } static VOID _DevPath1394 ( IN OUT POOL_PRINT *Str, IN VOID *DevPath ) { F1394_DEVICE_PATH *F1394; F1394 = DevPath; // Guid has format of IEEE-EUI64 CatPrint(Str, L"I1394(%016lx)", F1394->Guid); } static VOID _DevPathUsb ( IN OUT POOL_PRINT *Str, IN VOID *DevPath ) { USB_DEVICE_PATH *Usb; Usb = DevPath; CatPrint( Str , L"Usb(0x%x,0x%x)" , Usb-> Port , Usb-> Endpoint ) ; } static VOID _DevPathI2O ( IN OUT POOL_PRINT *Str, IN VOID *DevPath ) { I2O_DEVICE_PATH *I2O; I2O = DevPath; CatPrint(Str, L"I2O(0x%X)", I2O->Tid); } static VOID _DevPathMacAddr ( IN OUT POOL_PRINT *Str, IN VOID *DevPath ) { MAC_ADDR_DEVICE_PATH *MAC; UINTN HwAddressSize; UINTN Index; MAC = DevPath; /* HwAddressSize = sizeof(EFI_MAC_ADDRESS); */ HwAddressSize = DevicePathNodeLength( & MAC-> Header ) ; HwAddressSize -= sizeof( MAC-> Header ) ; HwAddressSize -= sizeof( MAC-> IfType ) ; if (MAC->IfType == 0x01 || MAC->IfType == 0x00) { HwAddressSize = 6; } CatPrint(Str, L"Mac("); for(Index = 0; Index < HwAddressSize; Index++) { CatPrint(Str, L"%02x",MAC->MacAddress.Addr[Index]); } if ( MAC-> IfType != 0 ) { CatPrint(Str, L",%d" , MAC-> IfType ) ; } CatPrint(Str, L")"); } static VOID CatPrintIPv4( IN OUT POOL_PRINT * Str , IN EFI_IPv4_ADDRESS * Address ) { CatPrint( Str , L"%d.%d.%d.%d" , Address-> Addr[ 0 ] , Address-> Addr[ 1 ] , Address-> Addr[ 2 ] , Address-> Addr[ 3 ] ) ; } static BOOLEAN IsNotNullIPv4( IN EFI_IPv4_ADDRESS * Address ) { UINT8 val ; val = Address-> Addr[ 0 ] | Address-> Addr[ 1 ] ; val |= Address-> Addr[ 2 ] | Address-> Addr[ 3 ] ; return val != 0 ; } static VOID CatPrintNetworkProtocol( IN OUT POOL_PRINT * Str , IN UINT16 Proto ) { if ( Proto == 6 ) { CatPrint( Str , L"TCP" ) ; } else if ( Proto == 17 ) { CatPrint( Str , L"UDP" ) ; } else { CatPrint( Str , L"%d" , Proto ) ; } } static VOID _DevPathIPv4 ( IN OUT POOL_PRINT *Str, IN VOID *DevPath ) { IPv4_DEVICE_PATH *IP; BOOLEAN show ; IP = DevPath; CatPrint( Str , L"IPv4(") ; CatPrintIPv4( Str , & IP-> RemoteIpAddress ) ; CatPrint( Str , L",") ; CatPrintNetworkProtocol( Str , IP-> Protocol ) ; CatPrint( Str , L",%s" , IP-> StaticIpAddress ? L"Static" : L"DHCP" ) ; show = IsNotNullIPv4( & IP-> LocalIpAddress ) ; if ( ! show && DevicePathNodeLength( & IP-> Header ) == sizeof( IPv4_DEVICE_PATH ) ) { /* only version 2 includes gateway and netmask */ show |= IsNotNullIPv4( & IP-> GatewayIpAddress ) ; show |= IsNotNullIPv4( & IP-> SubnetMask ) ; } if ( show ) { CatPrint( Str , L"," ) ; CatPrintIPv4( Str , & IP-> LocalIpAddress ) ; if ( DevicePathNodeLength( & IP-> Header ) == sizeof( IPv4_DEVICE_PATH ) ) { /* only version 2 includes gateway and netmask */ show = IsNotNullIPv4( & IP-> GatewayIpAddress ) ; show |= IsNotNullIPv4( & IP-> SubnetMask ) ; if ( show ) { CatPrint( Str , L",") ; CatPrintIPv4( Str , & IP-> GatewayIpAddress ) ; if ( IsNotNullIPv4( & IP-> SubnetMask ) ) { CatPrint( Str , L",") ; CatPrintIPv4( Str , & IP-> SubnetMask ) ; } } } } CatPrint( Str , L")") ; } #define CatPrintIPv6_ADD( x , y ) ( ( (UINT16) ( x ) ) << 8 | ( y ) ) static VOID CatPrintIPv6( IN OUT POOL_PRINT * Str , IN EFI_IPv6_ADDRESS * Address ) { CatPrint( Str , L"%x:%x:%x:%x:%x:%x:%x:%x" , CatPrintIPv6_ADD( Address-> Addr[ 0 ] , Address-> Addr[ 1 ] ) , CatPrintIPv6_ADD( Address-> Addr[ 2 ] , Address-> Addr[ 3 ] ) , CatPrintIPv6_ADD( Address-> Addr[ 4 ] , Address-> Addr[ 5 ] ) , CatPrintIPv6_ADD( Address-> Addr[ 6 ] , Address-> Addr[ 7 ] ) , CatPrintIPv6_ADD( Address-> Addr[ 8 ] , Address-> Addr[ 9 ] ) , CatPrintIPv6_ADD( Address-> Addr[ 10 ] , Address-> Addr[ 11 ] ) , CatPrintIPv6_ADD( Address-> Addr[ 12 ] , Address-> Addr[ 13 ] ) , CatPrintIPv6_ADD( Address-> Addr[ 14 ] , Address-> Addr[ 15 ] ) ) ; } static VOID _DevPathIPv6 ( IN OUT POOL_PRINT *Str, IN VOID *DevPath ) { IPv6_DEVICE_PATH *IP; IP = DevPath; CatPrint( Str , L"IPv6(") ; CatPrintIPv6( Str , & IP-> RemoteIpAddress ) ; CatPrint( Str , L",") ; CatPrintNetworkProtocol( Str, IP-> Protocol ) ; CatPrint( Str , L",%s," , IP-> IPAddressOrigin ? ( IP-> IPAddressOrigin == 1 ? L"StatelessAutoConfigure" : L"StatefulAutoConfigure" ) : L"Static" ) ; CatPrintIPv6( Str , & IP-> LocalIpAddress ) ; if ( DevicePathNodeLength( & IP-> Header ) == sizeof( IPv6_DEVICE_PATH ) ) { CatPrint( Str , L",") ; CatPrintIPv6( Str , & IP-> GatewayIpAddress ) ; CatPrint( Str , L",") ; CatPrint( Str , L"%d" , & IP-> PrefixLength ) ; } CatPrint( Str , L")") ; } static VOID _DevPathUri ( IN OUT POOL_PRINT *Str, IN VOID *DevPath ) { URI_DEVICE_PATH *Uri; Uri = DevPath; CatPrint( Str, L"Uri(%a)", Uri->Uri ); } static VOID _DevPathInfiniBand ( IN OUT POOL_PRINT *Str, IN VOID *DevPath ) { INFINIBAND_DEVICE_PATH *InfiniBand; InfiniBand = DevPath; CatPrint(Str, L"Infiniband(0x%x,%g,0x%lx,0x%lx,0x%lx)", InfiniBand->ResourceFlags, InfiniBand->PortGid, InfiniBand->ServiceId, InfiniBand->TargetPortId, InfiniBand->DeviceId); } static VOID _DevPathUart ( IN OUT POOL_PRINT *Str, IN VOID *DevPath ) { UART_DEVICE_PATH *Uart; CHAR8 Parity; Uart = DevPath; switch (Uart->Parity) { case 0 : Parity = 'D'; break; case 1 : Parity = 'N'; break; case 2 : Parity = 'E'; break; case 3 : Parity = 'O'; break; case 4 : Parity = 'M'; break; case 5 : Parity = 'S'; break; default : Parity = 'x'; break; } if (Uart->BaudRate == 0) { CatPrint(Str, L"Uart(DEFAULT,"); } else { CatPrint(Str, L"Uart(%ld,", Uart->BaudRate); } if (Uart->DataBits == 0) { CatPrint(Str, L"DEFAULT,"); } else { CatPrint(Str, L"%d,", Uart->DataBits); } CatPrint(Str, L"%c,", Parity); switch (Uart->StopBits) { case 0 : CatPrint(Str, L"D)"); break; case 1 : CatPrint(Str, L"1)"); break; case 2 : CatPrint(Str, L"1.5)"); break; case 3 : CatPrint(Str, L"2)"); break; default : CatPrint(Str, L"x)"); break; } } static VOID _DevPathSata ( IN OUT POOL_PRINT *Str, IN VOID *DevPath ) { SATA_DEVICE_PATH * Sata ; Sata = DevPath; CatPrint( Str , L"Sata(0x%x,0x%x,0x%x)" , Sata-> HBAPortNumber , Sata-> PortMultiplierPortNumber , Sata-> Lun ) ; } static VOID _DevPathHardDrive ( IN OUT POOL_PRINT *Str, IN VOID *DevPath ) { HARDDRIVE_DEVICE_PATH *Hd; Hd = DevPath; switch (Hd->SignatureType) { case SIGNATURE_TYPE_MBR: CatPrint(Str, L"HD(%d,MBR,0x%08x)", Hd->PartitionNumber, *((UINT32 *)(&(Hd->Signature[0]))) ); break; case SIGNATURE_TYPE_GUID: CatPrint(Str, L"HD(%d,GPT,%g)", Hd->PartitionNumber, (EFI_GUID *) &(Hd->Signature[0]) ); break; default: CatPrint(Str, L"HD(%d,%d,0)", Hd->PartitionNumber, Hd->SignatureType ); break; } } static VOID _DevPathCDROM ( IN OUT POOL_PRINT *Str, IN VOID *DevPath ) { CDROM_DEVICE_PATH *Cd; Cd = DevPath; CatPrint( Str , L"CDROM(0x%x)" , Cd-> BootEntry ) ; } static VOID _DevPathFilePath ( IN OUT POOL_PRINT *Str, IN VOID *DevPath ) { FILEPATH_DEVICE_PATH *Fp; Fp = DevPath; CatPrint(Str, L"%s", Fp->PathName); } static VOID _DevPathMediaProtocol ( IN OUT POOL_PRINT *Str, IN VOID *DevPath ) { MEDIA_PROTOCOL_DEVICE_PATH *MediaProt; MediaProt = DevPath; CatPrint(Str, L"%g", &MediaProt->Protocol); } static VOID _DevPathBssBss ( IN OUT POOL_PRINT *Str, IN VOID *DevPath ) { BBS_BBS_DEVICE_PATH *Bss; CHAR16 *Type; Bss = DevPath; switch (Bss->DeviceType) { case BBS_TYPE_FLOPPY: Type = L"Floppy"; break; case BBS_TYPE_HARDDRIVE: Type = L"Harddrive"; break; case BBS_TYPE_CDROM: Type = L"CDROM"; break; case BBS_TYPE_PCMCIA: Type = L"PCMCIA"; break; case BBS_TYPE_USB: Type = L"Usb"; break; case BBS_TYPE_EMBEDDED_NETWORK: Type = L"Net"; break; default: Type = L"?"; break; } CatPrint(Str, L"Bss-%s(%a)", Type, Bss->String); } static VOID _DevPathEndInstance ( IN OUT POOL_PRINT *Str, IN VOID *DevPath EFI_UNUSED ) { CatPrint(Str, L","); } /** * Print unknown device node. * UEFI 2.4 § 9.6.1.6 table 89. */ static VOID _DevPathNodeUnknown ( IN OUT POOL_PRINT *Str, IN VOID *DevPath ) { EFI_DEVICE_PATH * Path ; UINT8 * value ; int length , index ; Path = DevPath ; value = DevPath ; value += 4 ; switch ( Path-> Type ) { case HARDWARE_DEVICE_PATH : { /* Unknown Hardware Device Path */ CatPrint( Str , L"HardwarePath(%d" , Path-> SubType ) ; break ; } case ACPI_DEVICE_PATH : { /* Unknown ACPI Device Path */ CatPrint( Str , L"AcpiPath(%d" , Path-> SubType ) ; break ; } case MESSAGING_DEVICE_PATH : { /* Unknown Messaging Device Path */ CatPrint( Str , L"Msg(%d" , Path-> SubType ) ; break ; } case MEDIA_DEVICE_PATH : { /* Unknown Media Device Path */ CatPrint( Str , L"MediaPath(%d" , Path-> SubType ) ; break ; } case BBS_DEVICE_PATH : { /* Unknown BIOS Boot Specification Device Path */ CatPrint( Str , L"BbsPath(%d" , Path-> SubType ) ; break ; } default : { /* Unknown Device Path */ CatPrint( Str , L"Path(%d,%d" , Path-> Type , Path-> SubType ) ; break ; } } length = DevicePathNodeLength( Path ) ; for ( index = 0 ; index < length ; index ++ ) { if ( index == 0 ) CatPrint( Str , L",0x" ) ; CatPrint( Str , L"%02x" , * value ) ; value ++ ; } CatPrint( Str , L")" ) ; } /* * Table to convert "Type" and "SubType" to a "convert to text" function/ * Entries hold "Type" and "SubType" for know values. * Special "SubType" 0 is used as default for known type with unknown subtype. */ struct { UINT8 Type; UINT8 SubType; VOID (*Function)(POOL_PRINT *, VOID *); } DevPathTable[] = { { HARDWARE_DEVICE_PATH, HW_PCI_DP, _DevPathPci}, { HARDWARE_DEVICE_PATH, HW_PCCARD_DP, _DevPathPccard}, { HARDWARE_DEVICE_PATH, HW_MEMMAP_DP, _DevPathMemMap}, { HARDWARE_DEVICE_PATH, HW_VENDOR_DP, _DevPathVendor}, { HARDWARE_DEVICE_PATH, HW_CONTROLLER_DP, _DevPathController}, { ACPI_DEVICE_PATH, ACPI_DP, _DevPathAcpi}, { MESSAGING_DEVICE_PATH, MSG_ATAPI_DP, _DevPathAtapi}, { MESSAGING_DEVICE_PATH, MSG_SCSI_DP, _DevPathScsi}, { MESSAGING_DEVICE_PATH, MSG_FIBRECHANNEL_DP, _DevPathFibre}, { MESSAGING_DEVICE_PATH, MSG_1394_DP, _DevPath1394}, { MESSAGING_DEVICE_PATH, MSG_USB_DP, _DevPathUsb}, { MESSAGING_DEVICE_PATH, MSG_I2O_DP, _DevPathI2O}, { MESSAGING_DEVICE_PATH, MSG_MAC_ADDR_DP, _DevPathMacAddr}, { MESSAGING_DEVICE_PATH, MSG_IPv4_DP, _DevPathIPv4}, { MESSAGING_DEVICE_PATH, MSG_IPv6_DP, _DevPathIPv6}, { MESSAGING_DEVICE_PATH, MSG_URI_DP, _DevPathUri}, { MESSAGING_DEVICE_PATH, MSG_INFINIBAND_DP, _DevPathInfiniBand}, { MESSAGING_DEVICE_PATH, MSG_UART_DP, _DevPathUart}, { MESSAGING_DEVICE_PATH , MSG_SATA_DP , _DevPathSata } , { MESSAGING_DEVICE_PATH, MSG_VENDOR_DP, _DevPathVendor}, { MEDIA_DEVICE_PATH, MEDIA_HARDDRIVE_DP, _DevPathHardDrive}, { MEDIA_DEVICE_PATH, MEDIA_CDROM_DP, _DevPathCDROM}, { MEDIA_DEVICE_PATH, MEDIA_VENDOR_DP, _DevPathVendor}, { MEDIA_DEVICE_PATH, MEDIA_FILEPATH_DP, _DevPathFilePath}, { MEDIA_DEVICE_PATH, MEDIA_PROTOCOL_DP, _DevPathMediaProtocol}, { BBS_DEVICE_PATH, BBS_BBS_DP, _DevPathBssBss}, { END_DEVICE_PATH_TYPE, END_INSTANCE_DEVICE_PATH_SUBTYPE, _DevPathEndInstance}, { 0, 0, NULL} }; CHAR16 * DevicePathToStr ( EFI_DEVICE_PATH *DevPath ) /*++ Turns the Device Path into a printable string. Allcoates the string from pool. The caller must FreePool the returned string. --*/ { POOL_PRINT Str; EFI_DEVICE_PATH *DevPathNode; VOID (*DumpNode)(POOL_PRINT *, VOID *); UINTN Index, NewSize; ZeroMem(&Str, sizeof(Str)); // // Unpacked the device path // DevPath = UnpackDevicePath(DevPath); ASSERT (DevPath); // // Process each device path node // DevPathNode = DevPath; while (!IsDevicePathEnd(DevPathNode)) { // // Find the handler to dump this device path node // DumpNode = NULL; for (Index = 0; DevPathTable[Index].Function; Index += 1) { if (DevicePathType(DevPathNode) == DevPathTable[Index].Type && DevicePathSubType(DevPathNode) == DevPathTable[Index].SubType) { DumpNode = DevPathTable[Index].Function; break; } } // // If not found, use a generic function // if (!DumpNode) { DumpNode = _DevPathNodeUnknown; } // // Put a path seperator in if needed // if (Str.len && DumpNode != _DevPathEndInstance) { CatPrint (&Str, L"/"); } // // Print this node of the device path // DumpNode (&Str, DevPathNode); // // Next device path node // DevPathNode = NextDevicePathNode(DevPathNode); } // // Shrink pool used for string allocation // FreePool (DevPath); NewSize = (Str.len + 1) * sizeof(CHAR16); Str.str = ReallocatePool (Str.str, NewSize, NewSize); Str.str[Str.len] = 0; return Str.str; } BOOLEAN LibMatchDevicePaths ( IN EFI_DEVICE_PATH *Multi, IN EFI_DEVICE_PATH *Single ) { EFI_DEVICE_PATH *DevicePath, *DevicePathInst; UINTN Size; if (!Multi || !Single) { return FALSE; } DevicePath = Multi; while ((DevicePathInst = DevicePathInstance (&DevicePath, &Size))) { if (CompareMem (Single, DevicePathInst, Size) == 0) { return TRUE; } } return FALSE; } EFI_DEVICE_PATH * LibDuplicateDevicePathInstance ( IN EFI_DEVICE_PATH *DevPath ) { EFI_DEVICE_PATH *NewDevPath,*DevicePathInst,*Temp; UINTN Size = 0; // // get the size of an instance from the input // Temp = DevPath; DevicePathInst = DevicePathInstance (&Temp, &Size); // // Make a copy and set proper end type // NewDevPath = NULL; if (Size) { NewDevPath = AllocatePool (Size + sizeof(EFI_DEVICE_PATH)); } if (NewDevPath) { CopyMem (NewDevPath, DevicePathInst, Size); Temp = NextDevicePathNode(NewDevPath); SetDevicePathEndNode(Temp); } return NewDevPath; }
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
/*++ Copyright (c) 1998 Intel Corporation Module Name: hw.c Abstract: Debug library functions for Hardware IO access Revision History --*/ #include "lib.h" EFI_STATUS InitializeGlobalIoDevice ( IN EFI_DEVICE_PATH *DevicePath, IN EFI_GUID *Protocol, IN CHAR8 *ErrorStr EFI_UNUSED, OUT EFI_DEVICE_IO_INTERFACE **GlobalIoFncs ) /*++ Routine Description: Check to see if DevicePath exists for a given Protocol. Return Error if it exists. Return GlobalIoFuncs set match the DevicePath Arguments: DevicePath - to operate on Protocol - to check the DevicePath against ErrorStr - ASCII string to display on error GlobalIoFncs - Returned with DeviceIoProtocol for the DevicePath Returns: Pass or Fail based on wether GlobalIoFncs where found --*/ { EFI_STATUS Status; EFI_HANDLE Handle; // // Check to see if this device path already has Protocol on it. // if so we are loading recursivly and should exit with an error // Status = uefi_call_wrapper(BS->LocateDevicePath, 3, Protocol, &DevicePath, &Handle); if (!EFI_ERROR(Status)) { DEBUG ((D_INIT, "Device Already Loaded for %a device\n", ErrorStr)); return EFI_LOAD_ERROR; } Status = uefi_call_wrapper(BS->LocateDevicePath, 3, &DeviceIoProtocol, &DevicePath, &Handle); if (!EFI_ERROR(Status)) { Status = uefi_call_wrapper(BS->HandleProtocol, 3, Handle, &DeviceIoProtocol, (VOID*)GlobalIoFncs); } ASSERT (!EFI_ERROR(Status)); return Status; } UINT32 ReadPort ( IN EFI_DEVICE_IO_INTERFACE *GlobalIoFncs, IN EFI_IO_WIDTH Width, IN UINTN Port ) { UINT32 Data; EFI_STATUS Status EFI_UNUSED; Status = uefi_call_wrapper(GlobalIoFncs->Io.Read, 5, GlobalIoFncs, Width, (UINT64)Port, 1, &Data); ASSERT(!EFI_ERROR(Status)); return Data; } UINT32 WritePort ( IN EFI_DEVICE_IO_INTERFACE *GlobalIoFncs, IN EFI_IO_WIDTH Width, IN UINTN Port, IN UINTN Data ) { EFI_STATUS Status EFI_UNUSED; Status = uefi_call_wrapper(GlobalIoFncs->Io.Write, 5, GlobalIoFncs, Width, (UINT64)Port, 1, &Data); ASSERT(!EFI_ERROR(Status)); return (UINT32)Data; } UINT32 ReadPciConfig ( IN EFI_DEVICE_IO_INTERFACE *GlobalIoFncs, IN EFI_IO_WIDTH Width, IN UINTN Address ) { UINT32 Data; EFI_STATUS Status EFI_UNUSED; Status = uefi_call_wrapper(GlobalIoFncs->Pci.Read, 5, GlobalIoFncs, Width, (UINT64)Address, 1, &Data); ASSERT(!EFI_ERROR(Status)); return Data; } UINT32 WritePciConfig ( IN EFI_DEVICE_IO_INTERFACE *GlobalIoFncs, IN EFI_IO_WIDTH Width, IN UINTN Address, IN UINTN Data ) { EFI_STATUS Status EFI_UNUSED; Status = uefi_call_wrapper(GlobalIoFncs->Pci.Write, 5, GlobalIoFncs, Width, (UINT64)Address, 1, &Data); ASSERT(!EFI_ERROR(Status)); return (UINT32)Data; }
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
/*++ Copyright (c) 1998 Intel Corporation Module Name: event.c Abstract: Revision History --*/ #include "lib.h" EFI_EVENT LibCreateProtocolNotifyEvent ( IN EFI_GUID *ProtocolGuid, IN EFI_TPL NotifyTpl, IN EFI_EVENT_NOTIFY NotifyFunction, IN VOID *NotifyContext, OUT VOID *Registration ) { EFI_STATUS Status; EFI_EVENT Event; // // Create the event // Status = uefi_call_wrapper( BS->CreateEvent, 5, EVT_NOTIFY_SIGNAL, NotifyTpl, NotifyFunction, NotifyContext, &Event ); if ( EFI_ERROR( Status ) ) return NULL ; ASSERT (!EFI_ERROR(Status)); // // Register for protocol notifactions on this event // Status = uefi_call_wrapper( BS->RegisterProtocolNotify, 3, ProtocolGuid, Event, Registration ); if ( EFI_ERROR( Status ) ) return NULL ; ASSERT (!EFI_ERROR(Status)); // // Kick the event so we will perform an initial pass of // current installed drivers // uefi_call_wrapper(BS->SignalEvent, 1, Event); return Event; } EFI_STATUS WaitForSingleEvent ( IN EFI_EVENT Event, IN UINT64 Timeout OPTIONAL ) { EFI_STATUS Status; UINTN Index; EFI_EVENT TimerEvent; EFI_EVENT WaitList[2]; if (Timeout) { // // Create a timer event // Status = uefi_call_wrapper(BS->CreateEvent, 5, EVT_TIMER, 0, NULL, NULL, &TimerEvent); if (!EFI_ERROR(Status)) { // // Set the timer event // uefi_call_wrapper(BS->SetTimer, 3, TimerEvent, TimerRelative, Timeout); // // Wait for the original event or the timer // WaitList[0] = Event; WaitList[1] = TimerEvent; Status = uefi_call_wrapper(BS->WaitForEvent, 3, 2, WaitList, &Index); uefi_call_wrapper(BS->CloseEvent, 1, TimerEvent); // // If the timer expired, change the return to timed out // if (!EFI_ERROR(Status) && Index == 1) { Status = EFI_TIMEOUT; } } } else { // // No timeout... just wait on the event // Status = uefi_call_wrapper(BS->WaitForEvent, 3, 1, &Event, &Index); ASSERT (!EFI_ERROR(Status)); ASSERT (Index == 0); } return Status; } VOID WaitForEventWithTimeout ( IN EFI_EVENT Event, IN UINTN Timeout, IN UINTN Row, IN UINTN Column, IN CHAR16 *String, IN EFI_INPUT_KEY TimeoutKey, OUT EFI_INPUT_KEY *Key ) { EFI_STATUS Status; do { PrintAt (Column, Row, String, Timeout); Status = WaitForSingleEvent (Event, 10000000); if (Status == EFI_SUCCESS) { if (!EFI_ERROR(uefi_call_wrapper(ST->ConIn->ReadKeyStroke, 2, ST->ConIn, Key))) { return; } } } while (Timeout > 0); CopyMem(Key, &TimeoutKey, sizeof(EFI_INPUT_KEY)); }
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
/*++ Copyright (c) 1998 Intel Corporation Module Name: print.c Abstract: Revision History --*/ #include "lib.h" #include "efistdarg.h" // !!! // // Declare runtime functions // #ifdef RUNTIME_CODE #ifndef __GNUC__ #pragma RUNTIME_CODE(DbgPrint) // For debugging.. /* #pragma RUNTIME_CODE(_Print) #pragma RUNTIME_CODE(PFLUSH) #pragma RUNTIME_CODE(PSETATTR) #pragma RUNTIME_CODE(PPUTC) #pragma RUNTIME_CODE(PGETC) #pragma RUNTIME_CODE(PITEM) #pragma RUNTIME_CODE(ValueToHex) #pragma RUNTIME_CODE(ValueToString) #pragma RUNTIME_CODE(TimeToString) */ #endif /* !defined(__GNUC__) */ #endif // // // #define PRINT_STRING_LEN 200 #define PRINT_ITEM_BUFFER_LEN 100 typedef struct { BOOLEAN Ascii; UINTN Index; union { CONST CHAR16 *pw; CONST CHAR8 *pc; } un; } POINTER; #define pw un.pw #define pc un.pc typedef struct _pitem { POINTER Item; CHAR16 Scratch[PRINT_ITEM_BUFFER_LEN]; UINTN Width; UINTN FieldWidth; UINTN *WidthParse; CHAR16 Pad; BOOLEAN PadBefore; BOOLEAN Comma; BOOLEAN Long; } PRINT_ITEM; typedef struct _pstate { // Input POINTER fmt; va_list args; // Output CHAR16 *Buffer; CHAR16 *End; CHAR16 *Pos; UINTN Len; UINTN Attr; UINTN RestoreAttr; UINTN AttrNorm; UINTN AttrHighlight; UINTN AttrError; INTN (EFIAPI *Output)(VOID *context, CHAR16 *str); INTN (EFIAPI *SetAttr)(VOID *context, UINTN attr); VOID *Context; // Current item being formatted struct _pitem *Item; } PRINT_STATE; // // Internal fucntions // STATIC UINTN _Print ( IN PRINT_STATE *ps ); STATIC UINTN _IPrint ( IN UINTN Column, IN UINTN Row, IN SIMPLE_TEXT_OUTPUT_INTERFACE *Out, IN CONST CHAR16 *fmt, IN CONST CHAR8 *fmta, IN va_list args ); STATIC INTN EFIAPI _DbgOut ( IN VOID *Context, IN CHAR16 *Buffer ); STATIC VOID PFLUSH ( IN OUT PRINT_STATE *ps ); STATIC VOID PPUTC ( IN OUT PRINT_STATE *ps, IN CHAR16 c ); STATIC VOID PITEM ( IN OUT PRINT_STATE *ps ); STATIC CHAR16 PGETC ( IN POINTER *p ); STATIC VOID PSETATTR ( IN OUT PRINT_STATE *ps, IN UINTN Attr ); // // // INTN EFIAPI _SPrint ( IN VOID *Context, IN CHAR16 *Buffer ); INTN EFIAPI _PoolPrint ( IN VOID *Context, IN CHAR16 *Buffer ); INTN DbgPrint ( IN INTN mask, IN CONST CHAR8 *fmt, ... ) /*++ Routine Description: Prints a formatted unicode string to the default StandardError console Arguments: mask - Bit mask of debug string. If a bit is set in the mask that is also set in EFIDebug the string is printed; otherwise, the string is not printed fmt - Format string Returns: Length of string printed to the StandardError console --*/ { SIMPLE_TEXT_OUTPUT_INTERFACE *DbgOut; PRINT_STATE ps; va_list args; UINTN back; UINTN attr; UINTN SavedAttribute; if (!(EFIDebug & mask)) { return 0; } va_start (args, fmt); ZeroMem (&ps, sizeof(ps)); ps.Output = _DbgOut; ps.fmt.Ascii = TRUE; ps.fmt.pc = fmt; va_copy(ps.args, args); ps.Attr = EFI_TEXT_ATTR(EFI_LIGHTGRAY, EFI_RED); DbgOut = LibRuntimeDebugOut; if (!DbgOut) { DbgOut = ST->StdErr; } if (DbgOut) { ps.Attr = DbgOut->Mode->Attribute; ps.Context = DbgOut; ps.SetAttr = (INTN (EFIAPI *)(VOID *, UINTN)) DbgOut->SetAttribute; } SavedAttribute = ps.Attr; back = (ps.Attr >> 4) & 0xf; ps.AttrNorm = EFI_TEXT_ATTR(EFI_LIGHTGRAY, back); ps.AttrHighlight = EFI_TEXT_ATTR(EFI_WHITE, back); ps.AttrError = EFI_TEXT_ATTR(EFI_YELLOW, back); attr = ps.AttrNorm; if (mask & D_WARN) { attr = ps.AttrHighlight; } if (mask & D_ERROR) { attr = ps.AttrError; } if (ps.SetAttr) { ps.Attr = attr; uefi_call_wrapper(ps.SetAttr, 2, ps.Context, attr); } _Print (&ps); va_end (ps.args); va_end (args); // // Restore original attributes // if (ps.SetAttr) { uefi_call_wrapper(ps.SetAttr, 2, ps.Context, SavedAttribute); } return 0; } STATIC INTN IsLocalPrint(void *func) { if (func == _DbgOut || func == _SPrint || func == _PoolPrint) return 1; return 0; } STATIC INTN EFIAPI _DbgOut ( IN VOID *Context, IN CHAR16 *Buffer ) // Append string worker for DbgPrint { SIMPLE_TEXT_OUTPUT_INTERFACE *DbgOut; DbgOut = Context; // if (!DbgOut && ST && ST->ConOut) { // DbgOut = ST->ConOut; // } if (DbgOut) { if (IsLocalPrint(DbgOut->OutputString)) DbgOut->OutputString(DbgOut, Buffer); else uefi_call_wrapper(DbgOut->OutputString, 2, DbgOut, Buffer); } return 0; } INTN EFIAPI _SPrint ( IN VOID *Context, IN CHAR16 *Buffer ) // Append string worker for SPrint, PoolPrint and CatPrint { UINTN len; POOL_PRINT *spc; spc = Context; len = StrLen(Buffer); // // Is the string is over the max truncate it // if (spc->len + len > spc->maxlen) { len = spc->maxlen - spc->len; } // // Append the new text // CopyMem (spc->str + spc->len, Buffer, len * sizeof(CHAR16)); spc->len += len; // // Null terminate it // if (spc->len < spc->maxlen) { spc->str[spc->len] = 0; } else if (spc->maxlen) { spc->str[spc->maxlen] = 0; } return 0; } INTN EFIAPI _PoolPrint ( IN VOID *Context, IN CHAR16 *Buffer ) // Append string worker for PoolPrint and CatPrint { UINTN newlen; POOL_PRINT *spc; spc = Context; newlen = spc->len + StrLen(Buffer) + 1; // // Is the string is over the max, grow the buffer // if (newlen > spc->maxlen) { // // Grow the pool buffer // newlen += PRINT_STRING_LEN; spc->maxlen = newlen; spc->str = ReallocatePool ( spc->str, spc->len * sizeof(CHAR16), spc->maxlen * sizeof(CHAR16) ); if (!spc->str) { spc->len = 0; spc->maxlen = 0; } } // // Append the new text // return _SPrint (Context, Buffer); } VOID _PoolCatPrint ( IN CONST CHAR16 *fmt, IN va_list args, IN OUT POOL_PRINT *spc, IN INTN (EFIAPI *Output)(VOID *context, CHAR16 *str) ) // Dispath function for SPrint, PoolPrint, and CatPrint { PRINT_STATE ps; ZeroMem (&ps, sizeof(ps)); ps.Output = Output; ps.Context = spc; ps.fmt.pw = fmt; va_copy(ps.args, args); _Print (&ps); va_end(ps.args); } UINTN VSPrint ( OUT CHAR16 *Str, IN UINTN StrSize, IN CONST CHAR16 *fmt, va_list args ) /*++ Routine Description: Prints a formatted unicode string to a buffer using a va_list Arguments: Str - Output buffer to print the formatted string into StrSize - Size of Str. String is truncated to this size. A size of 0 means there is no limit fmt - The format string args - va_list Returns: String length returned in buffer --*/ { POOL_PRINT spc; spc.str = Str; spc.maxlen = StrSize / sizeof(CHAR16) - 1; spc.len = 0; _PoolCatPrint (fmt, args, &spc, _SPrint); return spc.len; } UINTN SPrint ( OUT CHAR16 *Str, IN UINTN StrSize, IN CONST CHAR16 *fmt, ... ) /*++ Routine Description: Prints a formatted unicode string to a buffer Arguments: Str - Output buffer to print the formatted string into StrSize - Size of Str. String is truncated to this size. A size of 0 means there is no limit fmt - The format string Returns: String length returned in buffer --*/ { va_list args; UINTN len; va_start (args, fmt); len = VSPrint(Str, StrSize, fmt, args); va_end (args); return len; } CHAR16 * VPoolPrint ( IN CONST CHAR16 *fmt, va_list args ) /*++ Routine Description: Prints a formatted unicode string to allocated pool using va_list argument. The caller must free the resulting buffer. Arguments: fmt - The format string args - The arguments in va_list form Returns: Allocated buffer with the formatted string printed in it. The caller must free the allocated buffer. The buffer allocation is not packed. --*/ { POOL_PRINT spc; ZeroMem (&spc, sizeof(spc)); _PoolCatPrint (fmt, args, &spc, _PoolPrint); return spc.str; } CHAR16 * PoolPrint ( IN CONST CHAR16 *fmt, ... ) /*++ Routine Description: Prints a formatted unicode string to allocated pool. The caller must free the resulting buffer. Arguments: fmt - The format string Returns: Allocated buffer with the formatted string printed in it. The caller must free the allocated buffer. The buffer allocation is not packed. --*/ { va_list args; CHAR16 *pool; va_start (args, fmt); pool = VPoolPrint(fmt, args); va_end (args); return pool; } CHAR16 * CatPrint ( IN OUT POOL_PRINT *Str, IN CONST CHAR16 *fmt, ... ) /*++ Routine Description: Concatenates a formatted unicode string to allocated pool. The caller must free the resulting buffer. Arguments: Str - Tracks the allocated pool, size in use, and amount of pool allocated. fmt - The format string Returns: Allocated buffer with the formatted string printed in it. The caller must free the allocated buffer. The buffer allocation is not packed. --*/ { va_list args; va_start (args, fmt); _PoolCatPrint (fmt, args, Str, _PoolPrint); va_end (args); return Str->str; } UINTN Print ( IN CONST CHAR16 *fmt, ... ) /*++ Routine Description: Prints a formatted unicode string to the default console Arguments: fmt - Format string Returns: Length of string printed to the console --*/ { va_list args; UINTN back; va_start (args, fmt); back = _IPrint ((UINTN) -1, (UINTN) -1, ST->ConOut, fmt, NULL, args); va_end (args); return back; } UINTN VPrint ( IN CONST CHAR16 *fmt, va_list args ) /*++ Routine Description: Prints a formatted unicode string to the default console using a va_list Arguments: fmt - Format string args - va_list Returns: Length of string printed to the console --*/ { return _IPrint ((UINTN) -1, (UINTN) -1, ST->ConOut, fmt, NULL, args); } UINTN PrintAt ( IN UINTN Column, IN UINTN Row, IN CONST CHAR16 *fmt, ... ) /*++ Routine Description: Prints a formatted unicode string to the default console, at the supplied cursor position Arguments: Column, Row - The cursor position to print the string at fmt - Format string Returns: Length of string printed to the console --*/ { va_list args; UINTN back; va_start (args, fmt); back = _IPrint (Column, Row, ST->ConOut, fmt, NULL, args); va_end (args); return back; } UINTN IPrint ( IN SIMPLE_TEXT_OUTPUT_INTERFACE *Out, IN CONST CHAR16 *fmt, ... ) /*++ Routine Description: Prints a formatted unicode string to the specified console Arguments: Out - The console to print the string too fmt - Format string Returns: Length of string printed to the console --*/ { va_list args; UINTN back; va_start (args, fmt); back = _IPrint ((UINTN) -1, (UINTN) -1, Out, fmt, NULL, args); va_end (args); return back; } UINTN IPrintAt ( IN SIMPLE_TEXT_OUTPUT_INTERFACE *Out, IN UINTN Column, IN UINTN Row, IN CONST CHAR16 *fmt, ... ) /*++ Routine Description: Prints a formatted unicode string to the specified console, at the supplied cursor position Arguments: Out - The console to print the string to Column, Row - The cursor position to print the string at fmt - Format string Returns: Length of string printed to the console --*/ { va_list args; UINTN back; va_start (args, fmt); back = _IPrint (Column, Row, Out, fmt, NULL, args); va_end (args); return back; } UINTN _IPrint ( IN UINTN Column, IN UINTN Row, IN SIMPLE_TEXT_OUTPUT_INTERFACE *Out, IN CONST CHAR16 *fmt, IN CONST CHAR8 *fmta, IN va_list args ) // Display string worker for: Print, PrintAt, IPrint, IPrintAt { PRINT_STATE ps; UINTN back; ZeroMem (&ps, sizeof(ps)); ps.Context = Out; ps.Output = (INTN (EFIAPI *)(VOID *, CHAR16 *)) Out->OutputString; ps.SetAttr = (INTN (EFIAPI *)(VOID *, UINTN)) Out->SetAttribute; ps.Attr = Out->Mode->Attribute; back = (ps.Attr >> 4) & 0xF; ps.AttrNorm = EFI_TEXT_ATTR(EFI_LIGHTGRAY, back); ps.AttrHighlight = EFI_TEXT_ATTR(EFI_WHITE, back); ps.AttrError = EFI_TEXT_ATTR(EFI_YELLOW, back); if (fmt) { ps.fmt.pw = fmt; } else { ps.fmt.Ascii = TRUE; ps.fmt.pc = fmta; } va_copy(ps.args, args); if (Column != (UINTN) -1) { uefi_call_wrapper(Out->SetCursorPosition, 3, Out, Column, Row); } back = _Print (&ps); va_end(ps.args); return back; } UINTN APrint ( IN CONST CHAR8 *fmt, ... ) /*++ Routine Description: For those whom really can't deal with unicode, a print function that takes an ascii format string Arguments: fmt - ascii format string Returns: Length of string printed to the console --*/ { va_list args; UINTN back; va_start (args, fmt); back = _IPrint ((UINTN) -1, (UINTN) -1, ST->ConOut, NULL, fmt, args); va_end (args); return back; } STATIC VOID PFLUSH ( IN OUT PRINT_STATE *ps ) { *ps->Pos = 0; if (IsLocalPrint(ps->Output)) ps->Output(ps->Context, ps->Buffer); else uefi_call_wrapper(ps->Output, 2, ps->Context, ps->Buffer); ps->Pos = ps->Buffer; } STATIC VOID PSETATTR ( IN OUT PRINT_STATE *ps, IN UINTN Attr ) { PFLUSH (ps); ps->RestoreAttr = ps->Attr; if (ps->SetAttr) { uefi_call_wrapper(ps->SetAttr, 2, ps->Context, Attr); } ps->Attr = Attr; } STATIC VOID PPUTC ( IN OUT PRINT_STATE *ps, IN CHAR16 c ) { // if this is a newline, add a carraige return if (c == '\n') { PPUTC (ps, '\r'); } *ps->Pos = c; ps->Pos += 1; ps->Len += 1; // if at the end of the buffer, flush it if (ps->Pos >= ps->End) { PFLUSH(ps); } } STATIC CHAR16 PGETC ( IN POINTER *p ) { CHAR16 c; c = p->Ascii ? p->pc[p->Index] : p->pw[p->Index]; p->Index += 1; return c; } STATIC VOID PITEM ( IN OUT PRINT_STATE *ps ) { UINTN Len, i; PRINT_ITEM *Item; CHAR16 c; // Get the length of the item Item = ps->Item; Item->Item.Index = 0; while (Item->Item.Index < Item->FieldWidth) { c = PGETC(&Item->Item); if (!c) { Item->Item.Index -= 1; break; } } Len = Item->Item.Index; // if there is no item field width, use the items width if (Item->FieldWidth == (UINTN) -1) { Item->FieldWidth = Len; } // if item is larger then width, update width if (Len > Item->Width) { Item->Width = Len; } // if pad field before, add pad char if (Item->PadBefore) { for (i=Item->Width; i < Item->FieldWidth; i+=1) { PPUTC (ps, ' '); } } // pad item for (i=Len; i < Item->Width; i++) { PPUTC (ps, Item->Pad); } // add the item Item->Item.Index=0; while (Item->Item.Index < Len) { PPUTC (ps, PGETC(&Item->Item)); } // If pad at the end, add pad char if (!Item->PadBefore) { for (i=Item->Width; i < Item->FieldWidth; i+=1) { PPUTC (ps, ' '); } } } STATIC UINTN _Print ( IN PRINT_STATE *ps ) /*++ Routine Description: %w.lF - w = width l = field width F = format of arg Args F: 0 - pad with zeros - - justify on left (default is on right) , - add comma's to field * - width provided on stack n - Set output attribute to normal (for this field only) h - Set output attribute to highlight (for this field only) e - Set output attribute to error (for this field only) l - Value is 64 bits a - ascii string s - unicode string X - fixed 8 byte value in hex x - hex value d - value as signed decimal u - value as unsigned decimal f - value as floating point c - Unicode char t - EFI time structure g - Pointer to GUID r - EFI status code (result code) D - pointer to Device Path with normal ending. N - Set output attribute to normal H - Set output attribute to highlight E - Set output attribute to error % - Print a % Arguments: SystemTable - The system table Returns: Number of charactors written --*/ { CHAR16 c; UINTN Attr; PRINT_ITEM Item; CHAR16 Buffer[PRINT_STRING_LEN]; ps->Len = 0; ps->Buffer = Buffer; ps->Pos = Buffer; ps->End = Buffer + PRINT_STRING_LEN - 1; ps->Item = &Item; ps->fmt.Index = 0; while ((c = PGETC(&ps->fmt))) { if (c != '%') { PPUTC ( ps, c ); continue; } // setup for new item Item.FieldWidth = (UINTN) -1; Item.Width = 0; Item.WidthParse = &Item.Width; Item.Pad = ' '; Item.PadBefore = TRUE; Item.Comma = FALSE; Item.Long = FALSE; Item.Item.Ascii = FALSE; Item.Item.pw = NULL; ps->RestoreAttr = 0; Attr = 0; while ((c = PGETC(&ps->fmt))) { switch (c) { case '%': // // %% -> % // Item.Scratch[0] = '%'; Item.Scratch[1] = 0; Item.Item.pw = Item.Scratch; break; case '0': Item.Pad = '0'; break; case '-': Item.PadBefore = FALSE; break; case ',': Item.Comma = TRUE; break; case '.': Item.WidthParse = &Item.FieldWidth; break; case '*': *Item.WidthParse = va_arg(ps->args, UINTN); break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': *Item.WidthParse = 0; do { *Item.WidthParse = *Item.WidthParse * 10 + c - '0'; c = PGETC(&ps->fmt); } while (c >= '0' && c <= '9') ; ps->fmt.Index -= 1; break; case 'a': Item.Item.pc = va_arg(ps->args, CHAR8 *); Item.Item.Ascii = TRUE; if (!Item.Item.pc) { Item.Item.pc = (CHAR8 *)"(null)"; } break; case 's': Item.Item.pw = va_arg(ps->args, CHAR16 *); if (!Item.Item.pw) { Item.Item.pw = L"(null)"; } break; case 'c': Item.Scratch[0] = (CHAR16) va_arg(ps->args, UINTN); Item.Scratch[1] = 0; Item.Item.pw = Item.Scratch; break; case 'l': Item.Long = TRUE; break; case 'X': Item.Width = Item.Long ? 16 : 8; Item.Pad = '0'; #if __GNUC__ >= 7 __attribute__ ((fallthrough)); #endif case 'x': ValueToHex ( Item.Scratch, Item.Long ? va_arg(ps->args, UINT64) : va_arg(ps->args, UINT32) ); Item.Item.pw = Item.Scratch; break; case 'g': GuidToString (Item.Scratch, va_arg(ps->args, EFI_GUID *)); Item.Item.pw = Item.Scratch; break; case 'u': ValueToString ( Item.Scratch, Item.Comma, Item.Long ? va_arg(ps->args, UINT64) : va_arg(ps->args, UINT32) ); Item.Item.pw = Item.Scratch; break; case 'd': ValueToString ( Item.Scratch, Item.Comma, Item.Long ? va_arg(ps->args, INT64) : va_arg(ps->args, INT32) ); Item.Item.pw = Item.Scratch; break; case 'D': { EFI_DEVICE_PATH *dp = va_arg(ps->args, EFI_DEVICE_PATH *); CHAR16 *dpstr = DevicePathToStr(dp); StrnCpy(Item.Scratch, dpstr, PRINT_ITEM_BUFFER_LEN); Item.Scratch[PRINT_ITEM_BUFFER_LEN-1] = L'\0'; FreePool(dpstr); Item.Item.pw = Item.Scratch; break; } case 'f': FloatToString ( Item.Scratch, Item.Comma, va_arg(ps->args, double) ); Item.Item.pw = Item.Scratch; break; case 't': TimeToString (Item.Scratch, va_arg(ps->args, EFI_TIME *)); Item.Item.pw = Item.Scratch; break; case 'r': StatusToString (Item.Scratch, va_arg(ps->args, EFI_STATUS)); Item.Item.pw = Item.Scratch; break; case 'n': PSETATTR(ps, ps->AttrNorm); break; case 'h': PSETATTR(ps, ps->AttrHighlight); break; case 'e': PSETATTR(ps, ps->AttrError); break; case 'N': Attr = ps->AttrNorm; break; case 'H': Attr = ps->AttrHighlight; break; case 'E': Attr = ps->AttrError; break; default: Item.Scratch[0] = '?'; Item.Scratch[1] = 0; Item.Item.pw = Item.Scratch; break; } // if we have an Item if (Item.Item.pw) { PITEM (ps); break; } // if we have an Attr set if (Attr) { PSETATTR(ps, Attr); ps->RestoreAttr = 0; break; } } if (ps->RestoreAttr) { PSETATTR(ps, ps->RestoreAttr); } } // Flush buffer PFLUSH (ps); return ps->Len; } STATIC CHAR8 Hex[] = {'0','1','2','3','4','5','6','7', '8','9','A','B','C','D','E','F'}; VOID ValueToHex ( IN CHAR16 *Buffer, IN UINT64 v ) { CHAR8 str[30], *p1; CHAR16 *p2; if (!v) { Buffer[0] = '0'; Buffer[1] = 0; return ; } p1 = str; p2 = Buffer; while (v) { // Without the cast, the MSVC compiler may insert a reference to __allmull *(p1++) = Hex[(UINTN)(v & 0xf)]; v = RShiftU64 (v, 4); } while (p1 != str) { *(p2++) = *(--p1); } *p2 = 0; } VOID ValueToString ( IN CHAR16 *Buffer, IN BOOLEAN Comma, IN INT64 v ) { STATIC CHAR8 ca[] = { 3, 1, 2 }; CHAR8 str[40], *p1; CHAR16 *p2; UINTN c, r; if (!v) { Buffer[0] = '0'; Buffer[1] = 0; return ; } p1 = str; p2 = Buffer; if (v < 0) { *(p2++) = '-'; v = -v; } while (v) { v = (INT64)DivU64x32 ((UINT64)v, 10, &r); *(p1++) = (CHAR8)r + '0'; } c = (Comma ? ca[(p1 - str) % 3] : 999) + 1; while (p1 != str) { c -= 1; if (!c) { *(p2++) = ','; c = 3; } *(p2++) = *(--p1); } *p2 = 0; } VOID FloatToString ( IN CHAR16 *Buffer, IN BOOLEAN Comma, IN double v ) { /* * Integer part. */ INTN i = (INTN)v; ValueToString(Buffer, Comma, i); /* * Decimal point. */ UINTN x = StrLen(Buffer); Buffer[x] = L'.'; x++; /* * Keep fractional part. */ float f = (float)(v - i); if (f < 0) f = -f; /* * Leading fractional zeroes. */ f *= 10.0; while ( (f != 0) && ((INTN)f == 0)) { Buffer[x] = L'0'; x++; f *= 10.0; } /* * Fractional digits. */ while ((float)(INTN)f != f) { f *= 10; } ValueToString(Buffer + x, FALSE, (INTN)f); return; } VOID TimeToString ( OUT CHAR16 *Buffer, IN EFI_TIME *Time ) { UINTN Hour, Year; CHAR16 AmPm; AmPm = 'a'; Hour = Time->Hour; if (Time->Hour == 0) { Hour = 12; } else if (Time->Hour >= 12) { AmPm = 'p'; if (Time->Hour >= 13) { Hour -= 12; } } Year = Time->Year % 100; // bugbug: for now just print it any old way SPrint (Buffer, 0, L"%02d/%02d/%02d %02d:%02d%c", Time->Month, Time->Day, Year, Hour, Time->Minute, AmPm ); } VOID DumpHex ( IN UINTN Indent, IN UINTN Offset, IN UINTN DataSize, IN VOID *UserData ) { CHAR8 *Data, Val[50], Str[20], c; UINTN Size, Index; UINTN ScreenCount; UINTN TempColumn; UINTN ScreenSize; CHAR16 ReturnStr[1]; uefi_call_wrapper(ST->ConOut->QueryMode, 4, ST->ConOut, ST->ConOut->Mode->Mode, &TempColumn, &ScreenSize); ScreenCount = 0; ScreenSize -= 2; Data = UserData; while (DataSize) { Size = 16; if (Size > DataSize) { Size = DataSize; } for (Index=0; Index < Size; Index += 1) { c = Data[Index]; Val[Index*3+0] = Hex[c>>4]; Val[Index*3+1] = Hex[c&0xF]; Val[Index*3+2] = (Index == 7)?'-':' '; Str[Index] = (c < ' ' || c > 'z') ? '.' : c; } Val[Index*3] = 0; Str[Index] = 0; Print (L"%*a%X: %-.48a *%a*\n", Indent, "", Offset, Val, Str); Data += Size; Offset += Size; DataSize -= Size; ScreenCount++; if (ScreenCount >= ScreenSize && ScreenSize != 0) { // // If ScreenSize == 0 we have the console redirected so don't // block updates // ScreenCount = 0; Print (L"Press Enter to continue :"); Input (L"", ReturnStr, sizeof(ReturnStr)/sizeof(CHAR16)); Print (L"\n"); } } }
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
/*++ Copyright (c) 1998 Intel Corporation Module Name: misc.c Abstract: Revision History --*/ #include "lib.h" // // // VOID * AllocatePool ( IN UINTN Size ) { EFI_STATUS Status; VOID *p; Status = uefi_call_wrapper(BS->AllocatePool, 3, PoolAllocationType, Size, &p); if (EFI_ERROR(Status)) { DEBUG((D_ERROR, "AllocatePool: out of pool %x\n", Status)); p = NULL; } return p; } VOID * AllocateZeroPool ( IN UINTN Size ) { VOID *p; p = AllocatePool (Size); if (p) { ZeroMem (p, Size); } return p; } VOID * ReallocatePool ( IN VOID *OldPool, IN UINTN OldSize, IN UINTN NewSize ) { VOID *NewPool; NewPool = NULL; if (NewSize) { NewPool = AllocatePool (NewSize); } if (OldPool) { if (NewPool) { CopyMem (NewPool, OldPool, OldSize < NewSize ? OldSize : NewSize); } FreePool (OldPool); } return NewPool; } VOID FreePool ( IN VOID *Buffer ) { uefi_call_wrapper(BS->FreePool, 1, Buffer); } VOID ZeroMem ( IN VOID *Buffer, IN UINTN Size ) { RtZeroMem (Buffer, Size); } VOID SetMem ( IN VOID *Buffer, IN UINTN Size, IN UINT8 Value ) { RtSetMem (Buffer, Size, Value); } VOID CopyMem ( IN VOID *Dest, IN CONST VOID *Src, IN UINTN len ) { RtCopyMem (Dest, Src, len); } INTN CompareMem ( IN CONST VOID *Dest, IN CONST VOID *Src, IN UINTN len ) { return RtCompareMem (Dest, Src, len); } BOOLEAN GrowBuffer( IN OUT EFI_STATUS *Status, IN OUT VOID **Buffer, IN UINTN BufferSize ) /*++ Routine Description: Helper function called as part of the code needed to allocate the proper sized buffer for various EFI interfaces. Arguments: Status - Current status Buffer - Current allocated buffer, or NULL BufferSize - Current buffer size needed Returns: TRUE - if the buffer was reallocated and the caller should try the API again. --*/ { BOOLEAN TryAgain; // // If this is an initial request, buffer will be null with a new buffer size // if (!*Buffer && BufferSize) { *Status = EFI_BUFFER_TOO_SMALL; } // // If the status code is "buffer too small", resize the buffer // TryAgain = FALSE; if (*Status == EFI_BUFFER_TOO_SMALL) { if (*Buffer) { FreePool (*Buffer); } *Buffer = AllocatePool (BufferSize); if (*Buffer) { TryAgain = TRUE; } else { *Status = EFI_OUT_OF_RESOURCES; } } // // If there's an error, free the buffer // if (!TryAgain && EFI_ERROR(*Status) && *Buffer) { FreePool (*Buffer); *Buffer = NULL; } return TryAgain; } EFI_MEMORY_DESCRIPTOR * LibMemoryMap ( OUT UINTN *NoEntries, OUT UINTN *MapKey, OUT UINTN *DescriptorSize, OUT UINT32 *DescriptorVersion ) { EFI_STATUS Status; EFI_MEMORY_DESCRIPTOR *Buffer; UINTN BufferSize; // // Initialize for GrowBuffer loop // Status = EFI_SUCCESS; Buffer = NULL; BufferSize = sizeof(EFI_MEMORY_DESCRIPTOR); // // Call the real function // while (GrowBuffer (&Status, (VOID **) &Buffer, BufferSize)) { Status = uefi_call_wrapper(BS->GetMemoryMap, 5, &BufferSize, Buffer, MapKey, DescriptorSize, DescriptorVersion); } // // Convert buffer size to NoEntries // if (!EFI_ERROR(Status)) { *NoEntries = BufferSize / *DescriptorSize; } return Buffer; } VOID * LibGetVariableAndSize ( IN CHAR16 *Name, IN EFI_GUID *VendorGuid, OUT UINTN *VarSize ) { EFI_STATUS Status; VOID *Buffer; UINTN BufferSize; // // Initialize for GrowBuffer loop // Buffer = NULL; BufferSize = 100; // // Call the real function // while (GrowBuffer (&Status, &Buffer, BufferSize)) { Status = uefi_call_wrapper( RT->GetVariable, 5, Name, VendorGuid, NULL, &BufferSize, Buffer ); } if (Buffer) { *VarSize = BufferSize; } else { *VarSize = 0; } return Buffer; } VOID * LibGetVariable ( IN CHAR16 *Name, IN EFI_GUID *VendorGuid ) { UINTN VarSize; return LibGetVariableAndSize (Name, VendorGuid, &VarSize); } EFI_STATUS LibDeleteVariable ( IN CHAR16 *VarName, IN EFI_GUID *VarGuid ) { VOID *VarBuf; EFI_STATUS Status; VarBuf = LibGetVariable(VarName,VarGuid); Status = EFI_NOT_FOUND; if (VarBuf) { // // Delete variable from Storage // Status = uefi_call_wrapper( RT->SetVariable, 5, VarName, VarGuid, EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE, 0, NULL ); ASSERT (!EFI_ERROR(Status)); FreePool(VarBuf); } return (Status); } EFI_STATUS LibSetNVVariable ( IN CHAR16 *VarName, IN EFI_GUID *VarGuid, IN UINTN DataSize, IN VOID *Data ) { EFI_STATUS Status; Status = uefi_call_wrapper( RT->SetVariable, 5, VarName, VarGuid, EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE, DataSize, Data ); ASSERT (!EFI_ERROR(Status)); return (Status); } EFI_STATUS LibSetVariable ( IN CHAR16 *VarName, IN EFI_GUID *VarGuid, IN UINTN DataSize, IN VOID *Data ) { EFI_STATUS Status; Status = uefi_call_wrapper( RT->SetVariable, 5, VarName, VarGuid, EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS, DataSize, Data ); ASSERT (!EFI_ERROR(Status)); return (Status); } EFI_STATUS LibInsertToTailOfBootOrder ( IN UINT16 BootOption, IN BOOLEAN OnlyInsertIfEmpty ) { UINT16 *BootOptionArray; UINT16 *NewBootOptionArray; UINTN VarSize; UINTN Index; EFI_STATUS Status; BootOptionArray = LibGetVariableAndSize (VarBootOrder, &EfiGlobalVariable, &VarSize); if (VarSize != 0 && OnlyInsertIfEmpty) { if (BootOptionArray) { FreePool (BootOptionArray); } return EFI_UNSUPPORTED; } VarSize += sizeof(UINT16); NewBootOptionArray = AllocatePool (VarSize); for (Index = 0; Index < ((VarSize/sizeof(UINT16)) - 1); Index++) { NewBootOptionArray[Index] = BootOptionArray[Index]; } // // Insert in the tail of the array // NewBootOptionArray[Index] = BootOption; Status = uefi_call_wrapper( RT->SetVariable, 5, VarBootOrder, &EfiGlobalVariable, EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE, VarSize, (VOID*) NewBootOptionArray ); if (NewBootOptionArray) { FreePool (NewBootOptionArray); } if (BootOptionArray) { FreePool (BootOptionArray); } return Status; } BOOLEAN ValidMBR( IN MASTER_BOOT_RECORD *Mbr, IN EFI_BLOCK_IO *BlkIo ) { UINT32 StartingLBA, EndingLBA; UINT32 NewEndingLBA; INTN i, j; BOOLEAN ValidMbr; if (Mbr->Signature != MBR_SIGNATURE) { // // The BPB also has this signature, so it can not be used alone. // return FALSE; } ValidMbr = FALSE; for (i=0; i<MAX_MBR_PARTITIONS; i++) { if ( Mbr->Partition[i].OSIndicator == 0x00 || EXTRACT_UINT32(Mbr->Partition[i].SizeInLBA) == 0 ) { continue; } ValidMbr = TRUE; StartingLBA = EXTRACT_UINT32(Mbr->Partition[i].StartingLBA); EndingLBA = StartingLBA + EXTRACT_UINT32(Mbr->Partition[i].SizeInLBA) - 1; if (EndingLBA > BlkIo->Media->LastBlock) { // // Compatability Errata: // Some systems try to hide drive space with thier INT 13h driver // This does not hide space from the OS driver. This means the MBR // that gets created from DOS is smaller than the MBR created from // a real OS (NT & Win98). This leads to BlkIo->LastBlock being // wrong on some systems FDISKed by the OS. // // if (BlkIo->Media->LastBlock < MIN_MBR_DEVICE_SIZE) { // // If this is a very small device then trust the BlkIo->LastBlock // return FALSE; } if (EndingLBA > (BlkIo->Media->LastBlock + MBR_ERRATA_PAD)) { return FALSE; } } for (j=i+1; j<MAX_MBR_PARTITIONS; j++) { if (Mbr->Partition[j].OSIndicator == 0x00 || EXTRACT_UINT32(Mbr->Partition[j].SizeInLBA) == 0) { continue; } if ( EXTRACT_UINT32(Mbr->Partition[j].StartingLBA) >= StartingLBA && EXTRACT_UINT32(Mbr->Partition[j].StartingLBA) <= EndingLBA ) { // // The Start of this region overlaps with the i'th region // return FALSE; } NewEndingLBA = EXTRACT_UINT32(Mbr->Partition[j].StartingLBA) + EXTRACT_UINT32(Mbr->Partition[j].SizeInLBA) - 1; if ( NewEndingLBA >= StartingLBA && NewEndingLBA <= EndingLBA ) { // // The End of this region overlaps with the i'th region // return FALSE; } } } // // Non of the regions overlapped so MBR is O.K. // return ValidMbr; } UINT8 DecimaltoBCD( IN UINT8 DecValue ) { return RtDecimaltoBCD (DecValue); } UINT8 BCDtoDecimal( IN UINT8 BcdValue ) { return RtBCDtoDecimal (BcdValue); } EFI_STATUS LibGetSystemConfigurationTable( IN EFI_GUID *TableGuid, IN OUT VOID **Table ) { UINTN Index; for(Index=0;Index<ST->NumberOfTableEntries;Index++) { if (CompareGuid(TableGuid,&(ST->ConfigurationTable[Index].VendorGuid))==0) { *Table = ST->ConfigurationTable[Index].VendorTable; return EFI_SUCCESS; } } return EFI_NOT_FOUND; } CHAR16 * LibGetUiString ( IN EFI_HANDLE Handle, IN UI_STRING_TYPE StringType, IN ISO_639_2 *LangCode, IN BOOLEAN ReturnDevicePathStrOnMismatch ) { UI_INTERFACE *Ui; UI_STRING_TYPE Index; UI_STRING_ENTRY *Array; EFI_STATUS Status; Status = uefi_call_wrapper(BS->HandleProtocol, 3, Handle, &UiProtocol, (VOID *)&Ui); if (EFI_ERROR(Status)) { return (ReturnDevicePathStrOnMismatch) ? DevicePathToStr(DevicePathFromHandle(Handle)) : NULL; } // // Skip the first strings // for (Index = UiDeviceString, Array = Ui->Entry; Index < StringType; Index++, Array++) { while (Array->LangCode) { Array++; } } // // Search for the match // while (Array->LangCode) { if (strcmpa (Array->LangCode, LangCode) == 0) { return Array->UiString; } } return (ReturnDevicePathStrOnMismatch) ? DevicePathToStr(DevicePathFromHandle(Handle)) : NULL; }
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
/*++ Copyright (c) 1998 Intel Corporation Module Name: crc.c Abstract: CRC32 functions Revision History --*/ #include "lib.h" UINT32 CRCTable[256] = { 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D }; VOID SetCrc ( IN OUT EFI_TABLE_HEADER *Hdr ) /*++ Routine Description: Updates the CRC32 value in the table header Arguments: Hdr - The table to update Returns: None --*/ { SetCrcAltSize (Hdr->HeaderSize, Hdr); } VOID SetCrcAltSize ( IN UINTN Size, IN OUT EFI_TABLE_HEADER *Hdr ) /*++ Routine Description: Updates the CRC32 value in the table header Arguments: Hdr - The table to update Returns: None --*/ { Hdr->CRC32 = 0; Hdr->CRC32 = CalculateCrc((UINT8 *)Hdr, Size); } BOOLEAN CheckCrc ( IN UINTN MaxSize, IN OUT EFI_TABLE_HEADER *Hdr ) /*++ Routine Description: Checks the CRC32 value in the table header Arguments: Hdr - The table to check Returns: TRUE if the CRC is OK in the table --*/ { return CheckCrcAltSize (MaxSize, Hdr->HeaderSize, Hdr); } BOOLEAN CheckCrcAltSize ( IN UINTN MaxSize, IN UINTN Size, IN OUT EFI_TABLE_HEADER *Hdr ) /*++ Routine Description: Checks the CRC32 value in the table header Arguments: Hdr - The table to check Returns: TRUE if the CRC is OK in the table --*/ { UINT32 Crc; UINT32 OrgCrc; BOOLEAN f; if (Size == 0) { // // If header size is 0 CRC will pass so return FALSE here // return FALSE; } if (MaxSize && Size > MaxSize) { DEBUG((D_ERROR, "CheckCrc32: Size > MaxSize\n")); return FALSE; } // clear old crc from header OrgCrc = Hdr->CRC32; Hdr->CRC32 = 0; Crc = CalculateCrc((UINT8 *)Hdr, Size); // set restults Hdr->CRC32 = OrgCrc; // return status f = OrgCrc == (UINT32) Crc; if (!f) { DEBUG((D_ERROR, "CheckCrc32: Crc check failed\n")); } return f; } UINT32 CalculateCrc ( UINT8 *pt, UINTN Size ) { UINTN Crc; // compute crc Crc = 0xffffffff; while (Size) { Crc = (Crc >> 8) ^ CRCTable[(UINT8) Crc ^ *pt]; pt += 1; Size -= 1; } Crc = Crc ^ 0xffffffff; return (UINT32)Crc; }
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }
/*++ Copyright (c) 2000 Intel Corporation Module Name: Smbios.c Abstract: Lib fucntions for SMBIOS. Used to get system serial number and GUID Revision History --*/ #include "lib.h" /* * We convert 32 bit values to pointers. In 64 bit mode the compiler will issue a * warning stating that the value is too small for the pointer: * "warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]" * we can safely ignore them here. */ #ifdef __GNUC__ #pragma GCC diagnostic ignored "-Wint-to-pointer-cast" #endif EFI_STATUS LibGetSmbiosSystemGuidAndSerialNumber ( IN EFI_GUID *SystemGuid, OUT CHAR8 **SystemSerialNumber ) { EFI_STATUS Status; SMBIOS_STRUCTURE_TABLE *SmbiosTable; SMBIOS_STRUCTURE_POINTER Smbios; SMBIOS_STRUCTURE_POINTER SmbiosEnd; UINT16 Index; Status = LibGetSystemConfigurationTable(&SMBIOSTableGuid, (VOID**)&SmbiosTable); if (EFI_ERROR(Status)) { return EFI_NOT_FOUND; } Smbios.Hdr = (SMBIOS_HEADER *)SmbiosTable->TableAddress; SmbiosEnd.Raw = (UINT8 *)(SmbiosTable->TableAddress + SmbiosTable->TableLength); for (Index = 0; Index < SmbiosTable->TableLength ; Index++) { if (Smbios.Hdr->Type == 1) { if (Smbios.Hdr->Length < 0x19) { // // Older version did not support Guid and Serial number // continue; } // // SMBIOS tables are byte packed so we need to do a byte copy to // prevend alignment faults on IA-64. CopyMem (SystemGuid, &Smbios.Type1->Uuid, sizeof(EFI_GUID)); *SystemSerialNumber = LibGetSmbiosString(&Smbios, Smbios.Type1->SerialNumber); return EFI_SUCCESS; } // // Make Smbios point to the next record // LibGetSmbiosString (&Smbios, -1); if (Smbios.Raw >= SmbiosEnd.Raw) { // // SMBIOS 2.1 incorrectly stated the length of SmbiosTable as 0x1e. // given this we must double check against the lenght of /// the structure. My home PC has this bug.ruthard // return EFI_SUCCESS; } } return EFI_SUCCESS; } CHAR8* LibGetSmbiosString ( IN SMBIOS_STRUCTURE_POINTER *Smbios, IN UINT16 StringNumber ) /*++ Return SMBIOS string given the string number. Arguments: Smbios - Pointer to SMBIOS structure StringNumber - String number to return. -1 is used to skip all strings and point to the next SMBIOS structure. Returns: Pointer to string, or pointer to next SMBIOS strcuture if StringNumber == -1 --*/ { UINT16 Index; CHAR8 *String; // // Skip over formatted section // String = (CHAR8 *)(Smbios->Raw + Smbios->Hdr->Length); // // Look through unformated section // for (Index = 1; Index <= StringNumber; Index++) { if (StringNumber == Index) { return String; } // // Skip string // for (; *String != 0; String++); String++; if (*String == 0) { // // If double NULL then we are done. // Retrun pointer to next structure in Smbios. // if you pass in a -1 you will always get here // Smbios->Raw = (UINT8 *)++String; return NULL; } } return NULL; }
{ "repo_name": "Absurdponcho/PonchoOS", "stars": "151", "repo_language": "C", "file_name": "kernel.c", "mime_type": "text/plain" }